ExamAdda Logo

Merge Sorted Array

Easy

You are given two sorted integer arrays nums1 and nums2, and two integers m and n representing the number of valid elements in nums1 and nums2 respectively.

The array nums1 has a size of m + n, where the last n elements are 0 and should be ignored. Merge nums2 into nums1 so that nums1 becomes a single sorted array in non-decreasing order.

Modify nums1 in-place.

Example 1

Input

3 3
1 2 3 0 0 0
2 5 6

Output

1 2 2 3 5 6

Explanation

After merging the two sorted arrays, nums1 becomes [1, 2, 2, 3, 5, 6].

Example 2

Input

1 0
1

Output

1

Explanation

Since nums2 is empty, nums1 remains unchanged.

Constraints

0 ≤ m
n ≤ 200
1 ≤ m + n ≤ 200
-10⁹ ≤ nums1[i]
nums2[i] ≤ 10⁹

Hints:

Hint 1

Start comparing elements from the end of both arrays instead of the beginning.

Hint 2

Use three pointers: one at the last valid element of nums1, one at the last element of nums2, and one at the last position of nums1. Fill nums1 from the back.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 1, 2026

Last updated

Aug 1, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output