Skip to the solution
EasyDSA7 min read

How do you merge two sorted arrays?

317 views

The problem

Question presented to candidate: "You are given two lists of integers, each already sorted in ascending order. Write a Python function that returns one sorted list containing every element of both. Then tell me how you would do it if the first list had empty slots at the end and I wanted the merge done in place."

What a strong answer should cover:

  • The two-pointer merge: compare the fronts, append the smaller, advance that pointer, then add the leftovers of whichever list is not used up.
  • O(m + n) time and O(m + n) output space, compared with O((m + n) log(m + n)) for re-sorting from scratch.
  • Using <= so equal items from the first list come first (a stable merge), and why that matters for records.
  • The in-place variant (LeetCode 88): fill nums1 from the back so nothing unread is overwritten; O(1) extra space.
  • Python specifics: result.extend(a[i:]) copies the tail (slicing makes a copy), heapq.merge exists and returns a lazy generator, and sorted(a + b) is correct but does more work than needed.

Clarifying questions expected:

  • "New list, or merge into the first list in place?"
  • "Can either list be empty, and can there be duplicates?"

Code / implementation expected: Yes โ€” a Python merge(a, b) with two indices, and ideally the from-the-back in-place version.

  • sorting
  • merge

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

7 min read ยท 11 sections

Python code

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

PythonTwo-pointer merge into a new array (several inputs, including empty ones)
PythonIn-place merge into nums1 by filling from the back
PythonStability (<= vs <) and counting comparisons

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 32 of 154 in DSA

Keep your momentum going.

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

All DSA questions
Up nextEasy

How do you find the majority element?

Continue