Lv.1countinghashsorting
Common Elements
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given two integer arrays a and b, return every element common to both, sorted in ascending order. A value that
repeats appears in the result as many times as the smaller of its counts in a and b. Return an empty array if
nothing is common.
Examples
| a | b | result |
|---|---|---|
[1, 2, 2, 1] | [2, 2] | [2, 2] |
[4, 9, 5] | [9, 4, 9, 8, 4] | [4, 9] |
[1, 3] | [2, 4] | [] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(a: int[], b: int[]) → int[]
Constraints
-
a.length,b.length -
a[i],b[j]
Expected complexity
- Time
- O(N log N + M log M)
- Space
- O(N + M)
Examples
| a | b | Expected |
|---|---|---|
[1,2,2,1] | [2,2] | [2,2] |
[4,9,5] | [9,4,9,8,4] | [4,9] |
[1,3] | [2,4] | [] |
Hint
Hint
Either count the values of a in a hash map and consume them while scanning b (then sort), or sort both arrays and walk
them with two pointers, emitting a value whenever the pointers meet equal elements. Searching b for each element of a is
and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1494 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 3 | verdict only |