05
SepMerge Sorted Arrays
The Merge Sorted Arrays Problem involves merging two sorted arrays into a single sorted array. Given two sorted arrays nums1 and nums2, merge them into a new sorted array without using extra space beyond what is needed for the output. This problem is often seen in the context of merging two sorted lists or as part of the merge step in Merge Sort.
Example
- Input: nums1 = [1, 3, 5], nums2 = [2, 4, 6]
- Output: [1, 2, 3, 4, 5, 6]
- Explanation: The merged array contains all elements from both arrays in sorted order.
Logic
Enter two sorted arrays of numbers (comma-separated) to merge them into a single sorted array.
Program (Python - Two-Pointer Approach)
The following Python code uses a two-pointer technique to merge two sorted arrays efficiently with O(n + m) time complexity, where n and m are the lengths of the input arrays.
def mergeSortedArrays(nums1, nums2):
result = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
result.append(nums1[i])
i += 1
else:
result.append(nums2[j])
j += 1
# Add remaining elements from nums1, if any
result.extend(nums1[i:])
# Add remaining elements from nums2, if any
result.extend(nums2[j:])
return result
# Example usage
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
print(mergeSortedArrays(nums1, nums2)) # Output: [1, 2, 3, 4, 5, 6]
Output
For the input nums1 = [1, 3, 5] and nums2 = [2, 4, 6], the output is:
[1, 2, 3, 4, 5, 6]
Explanation:
The arrays are merged into a single sorted array.
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.