MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

Java Program to Merge two sorted arrays into first with Explanation

Java Hard Arrays 22 views
This problem helps you practice core Java fundamentals in a practical way. It builds intuition around sorted, size, merge. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Task: a has size m+n, first m elements valid. b has n elements. Merge b into a in sorted order (in-place).

Input Format

Two integers m and n

Array a of size m + n (first m elements are valid, last n are empty)

Array b of size n

Both arrays are already sorted in non-decreasing order

Output Format

Array a after merging b into it in sorted order (in-place).

Constraints

• m ≥ 0, n ≥ 0

• Total size of a is exactly m + n

• Do not use extra array

• Merge must be done in-place

Concept Explanation

Both arrays are already sorted.
To merge in-place, we start filling a from the end,
so existing values are not overwritten.

Step-by-Step Logic

1.Set three pointers:

• i = m - 1 → last valid element in a

• j = n - 1 → last element in b

• k = m + n - 1 → last position in a
2.While i >= 0 and j >= 0:

• If a[i] > b[j]:

• Set a[k] = a[i]

• Decrement i

• Else:

• Set a[k] = b[j]

• Decrement j

• Decrement k
3.If elements remain in b:

• Copy them into a (remaining a elements are already in place)

4.Array a is now fully merged and sorted.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
static void mergeIntoA(int[] a,int m,int[] b,int n){int i=m-1,j=n-1,k=m+n-1;while(j>=0){if(i>=0 && a[i]>b[j]) a[k--]=a[i--];else a[k--]=b[j--];}}

Output Example

Input:
m = 3, n = 3 a = [1, 3, 5, 0, 0, 0] b = [2, 4, 6]
Output:
[1, 2, 3, 4, 5, 6]

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next