Skip to the solution
MediumDSAAsked in 20244 min read

Merge sorted arrays

1.3k views

The problem

Problem, as an interviewer would state it: "Merge two sorted arrays into one sorted array. Discuss edge cases, runtime, and how you would do it in place."

Examples:

Code
merge([1, 3, 5], [2, 4, 6]); // [1, 2, 3, 4, 5, 6]

Clarifying questions expected:

  • Sorted ascending? Numbers, or objects sorted by a key?
  • On ties, which element should come first (does stability matter)?
  • May I allocate a new array, or must it happen in place (LeetCode 88, where the first array has spare room at the end)?

Code / implementation expected: Yes — real, direct proof against a reference, plus stability and the in-place variant.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a two-pointer merge matches concat plus sort on random input, is stable on ties, and has an in-place form that fills from the back

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 79 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement promiseRetry(fn, retries, delay) with exponential backoff

Continue