Skip to main content

5. Merge Sorted Array

easyAsked at Swiggy

Merge nums2 into nums1 in-place so the result is sorted non-decreasing.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given two sorted arrays nums1 (length m+n, last n slots zero-padded) and nums2 (length n). Merge nums2 into nums1 so nums1 ends sorted. Mutate nums1 in-place.

Constraints

  • 0 <= m, n <= 200
  • nums1.length == m + n
  • Both inputs sorted non-decreasing

Examples

Example 1

Input
nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3
Output
[1,2,2,3,5,6]

Example 2

Input
nums1=[1], m=1, nums2=[], n=0
Output
[1]

Approaches

1. Concat and sort

Splice nums2 in then sort.

Time
O((m+n) log (m+n))
Space
O(1)
nums1.splice(m, n, ...nums2);
nums1.sort((a,b)=>a-b);

Tradeoff:

2. Three pointers from end

Walk both arrays from the largest end and write into the trailing slots of nums1. Writing right-to-left avoids overwriting unread data.

Time
O(m+n)
Space
O(1)
function merge(nums1, m, nums2, n) {
  let i = m - 1, j = n - 1, k = m + n - 1;
  while (j >= 0) {
    if (i >= 0 && nums1[i] > nums2[j]) {
      nums1[k--] = nums1[i--];
    } else {
      nums1[k--] = nums2[j--];
    }
  }
}

Tradeoff:

Swiggy-specific tips

Swiggy interviewers like this when they want to see if you reason from the tail; it sets up later questions about merging sorted courier ETA streams.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Merge Sorted Array and other Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →