Lv.1arraytwo-pointers
Merge Two Sorted Arrays
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Two arrays a and b are each sorted in non-decreasing order. Return one array, sorted in non-decreasing order, that contains
every element of both (duplicates kept).
Examples
| a | b | result |
|---|---|---|
[1, 4, 7] | [2, 3, 8, 9] | [1, 2, 3, 4, 7, 8, 9] |
[] | [5, 5] | [5, 5] |
[-3, 0, 0] | [0, 10] | [-3, 0, 0, 0, 10] |
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.length + b.length -
a[i],b[i] aandbare each sorted in non-decreasing order.
Expected complexity
- Time
- O(N + M)
- Space
- O(N + M)
Examples
| a | b | Expected |
|---|---|---|
[1,4,7] | [2,3,8,9] | [1,2,3,4,7,8,9] |
[] | [5,5] | [5,5] |
[-3,0,0] | [0,10] | [-3,0,0,0,10] |
Hint
Hint
Keep a pointer into each array and repeatedly take the smaller front element; when one runs out, append the rest of the other.
Inserting each element of b into a (shifting everything after it) 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 | 1592 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 | 4 | verdict only |