Arrays · Coding problem
Merge Sorted Array
A free coding problem from the Two Pointers skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
You are given two sorted integer arrays. The first, conceptually of length m + n, has its first m elements set and its last n elements available as placeholder space; the second has n elements. Merge the second array into the first in place, so the first array ends up sorted ascending, length m + n.
Input format
Line 1: m. Line 2: the m real elements of the first array (omitted if m = 0). Line 3: n. Line 4: the n elements of the second array (omitted if n = 0).
Example
Input:
4
-1 3 8 10
3
0 3 12
Output:
-1 0 3 3 8 10 12
Solve it in O(m + n) time, filling the first array from the back so you never overwrite a real element before reading it.
Constraints
0 <= m, n <= 2001 <= m + n <= 200-10^9 <= values <= 10^9
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Two Pointers
Solve it Merge Sorted Array free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime