Merge Sorted Arrays

Merge Sorted Arrays

01 Sep 2025
Beginner
20 Views
4 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

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.

GET FREE CHALLENGE

Share Article
About Author
Amit Kumar (Software Engineer And Author)

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.
Live Training - Book Free Demo
ASP.NET Core Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI Foundry Certification Training
06 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
React Certification Training
07 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure Developer Certification Training
08 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this