Skip to main content
All Questions

Merge two lists where one has empty spaces at the end.

Easy
Unlock detailed company stats for this questionUpgrade

You're given two arrays sorted in non-decreasing order, nums1 and nums2, and two integers m and n. The first m elements of nums1 are real values. Its last n slots hold 0 as placeholders, so nums1 has length m + n. nums2 has exactly n values.

Merge nums2 into nums1 so that nums1 ends up holding all m + n values in sorted order. Modify nums1 in place and don't return anything.

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]

The three zeros at the end of nums1 are space for the values from nums2.

Example 2

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

With m = 0, the 0 in nums1 is a placeholder, not a value.

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.