#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
DSA Practice Problems

Merge Sorted Arrays

Given two arrays that are already sorted, the goal is to combine them into a single sorted array (or merge one into the other in place) without using extra sorting of the whole combined array.

Two-Pointer Approach

Maintain a pointer for each array. Compare the elements the pointers point to, push the smaller one into the result, and advance that pointer. Continue until one array is exhausted, then append the remainder of the other.

def merge_sorted_arrays(a, b):
    i = j = 0
    merged = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            merged.append(a[i]); i += 1
        else:
            merged.append(b[j]); j += 1
    merged.extend(a[i:])
    merged.extend(b[j:])
    return merged

In-Place Variant (LeetCode Style)

When array A has enough trailing empty space to hold array B's elements, merge from the back to avoid overwriting unprocessed values.

Complexity

MetricValue
TimeO(m + n)
SpaceO(m + n) or O(1) for in-place

Applications

  • The merge step is the core building block of Merge Sort.
  • Merging sorted result sets from distributed/parallel computations.
  • Combining sorted log files or streams.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course