Scrivio Interview library
Two pointersArrays and stringsReported 47 times · 16 min read · updated 15 November 2026

Merge two sorted arrays into one sorted array.

1What it means to merge two sorted arrays

Picture a teacher holding two piles of exam papers. Each pile is already sorted by roll number, smallest on top, because two assistants sorted them separately. The teacher wants one pile, sorted from top to bottom. Nobody would throw both piles on the floor and start again. The natural way is to look at the top paper of each pile, pick up whichever has the smaller roll number, put it face down on a new pile, and look again. That everyday habit is the whole solution, and the rest of this article only turns it into careful Java.

In programming terms we are given two arrays, each sorted in ascending order, so every value is no larger than the one after it. We must return one array holding every value from both, also in ascending order. The problem is smaller than it looks: the sorting has already been done for us, twice, and we only have to weave the two runs together.

Let us fix one example for the whole article. Array a is [1, 4, 7, 9] and array b is [2, 4, 8]. The answer is [1, 2, 4, 4, 7, 8, 9]. Do it once by hand. Look at the fronts, 1 and 2, and write 1. Now the fronts are 4 and 2, so write 2. Then 4 and 4, a tie, so write one 4. Then 7 and 4, so write the other 4. Then 7 and 8, so write 7. Then 9 and 8, so write 8. Now b is empty, so write the 9 that is left. Each time we looked at only two numbers.

PictureThe two sorted arrays and the merged answer

Top row: array a. Middle row: array b. Bottom row: the single sorted array we must build from them.

  1. 14792481244789
    length of a
    4
    length of b
    3
    length of out
    7

    1a = [1, 4, 7, 9] and b = [2, 4, 8] are each sorted. The answer holds all seven values in order, and both 4s are kept.

What to assume

Do we return a new array, or merge into one of the inputs?
A new array.
Are duplicates kept?
Yes, both 4s appear in the answer.
When two values are equal, which one goes first?
The one from a, which keeps equal values in the order they started, a property called stability.
Can an array be empty?
Yes, and then the answer is simply a copy of the other one.

A careful candidate asks a few questions first. Do we return a new array, or merge into one of the inputs? We do the new array first, then the variant where a has empty slots at its end for b. Are duplicates kept? Yes, both 4s appear in the answer. When two values are equal, which one goes first? The one from a, which keeps equal values in the order they started, a property called stability. Can an array be empty? Yes, and then the answer is simply a copy of the other one.

2How to recognise a two pointers problem

When a beginner first reads this question, the word sorted takes over and the first thought is to reach for a sorting method. That is a reasonable instinct, and we will try it next. But a sort does not know the input was already half done, so let us read the question slowly and ask what the given order offers us.

The first clue is the word sorted in front of the inputs, not just the output. Because a is sorted, its smallest unused value is always the one at the front of the part we have not used yet. The same is true of b. So the smallest unused value of the two arrays together must be one of only two candidates, the front of a or the front of b. We never need to look further into either array to decide what comes next.

The second clue is that there are exactly two inputs and we must walk through both of them together. To walk through an array we need an index, a variable that remembers our position, like a finger resting on one paper in a pile. Two arrays need two fingers, one for each, and each finger only ever moves forward. A third index will remember where the next value goes in the output.

These clues point to the pattern called two pointers. A pointer here is just an index variable that marks a position in an array; Java has no raw pointers, so the name is borrowed from older languages. The two pointers technique keeps two such indexes and moves them by a simple rule, so that one pass over the data does the work. The general rule to carry to new problems is this: whenever you must combine two sorted sequences, whether by merging, intersecting, taking a union or finding a difference, walk them together with one index each and decide every step by comparing only the two current values.

Two look-alikes are worth separating. The other famous two pointers shape puts both indexes on one array, one at each end, moving towards each other, as in finding a pair with a given sum; here the indexes live in two arrays and both move forward. And with many sorted arrays, a min-heap, a structure that always hands back its smallest value, takes over, but with two arrays one comparison already finds the smaller front.

3The honest first attempt, joining the arrays and sorting them

When a problem feels new, it is wise to start with a solution we are sure is correct, even if it is slow. This brute force copies both arrays into one bigger array and lets the library sort it. It ignores the order we were given, but it is short and correct, and it gives us something to improve on.

By hand, the copy step gives [1, 4, 7, 9, 2, 4, 8], with b placed after a, and Arrays.sort rearranges it into [1, 2, 4, 4, 7, 8, 9]. The answer is right.

Java
static int[] mergeBySort(int[] a, int[] b) {
int[] out = Arrays.copyOf(a, a.length + b.length); // a first, then room for b
System.arraycopy(b, 0, out, a.length, b.length); // put b after a
Arrays.sort(out); // let the library sort everything
return out;
}

Now let us count the work. Copying is one step per value, seven here, or n + m in general if a has n values and b has m. Sorting is the expensive part: a good sort on N values needs about N times log N comparisons, where log N is roughly how many times you can halve N before reaching 1. For our seven values that is some twenty comparisons. We write the time as O((n + m) log(n + m)), read as order n plus m times log of n plus m. The output array needs n + m slots, so the space is O(n + m).

Where is the waste? The sort starts from scratch and rediscovers an order that was already there. Inside a, the 1 was already before the 4, the 4 before the 7, the 7 before the 9, and the sort spends comparisons learning that again. For two arrays of a million values each, a sort makes about forty million comparisons, while the hand method needs at most two million. The sort is paying again for work the two assistants already did.

When we merged by hand, how many values did we look at before writing each one? Just two, the two fronts, and that is what the sort throws away.

4Getting to the two pointer merge, one observation at a time

Let us build the merge slowly from what we noticed. We keep an index i into a and an index j into b, both starting at 0, so a[i] and b[j] are the two fronts. We also keep k, the next free position in the output array, starting at 0. At each step we compare a[i] with b[j], copy the smaller into out[k], and move forward the index of the array we took from, together with k. The other index stays still, because its value has not been used yet and is still waiting for its turn.

Here a beginner usually asks why it is safe to write the smaller front straight into the output without checking the rest of the arrays. Think of the exam papers. Every paper still in pile a has a roll number at least as large as a's top paper, because the pile is sorted, and the same holds for pile b. So the smaller of the two top papers is no larger than any paper left anywhere, and it must come next. Putting it down can never be a mistake. Said more formally, out[0] to out[k - 1] always holds the k smallest values of both arrays in sorted order, and each step keeps that true.

Ties need one decision. When a[i] equals b[j], either choice gives a sorted result, but taking from a keeps equal values in their starting order, which matters when the numbers are keys of larger records. So we write the test as a[i] <= b[j] rather than a[i] < b[j].

The second question beginners ask is what happens when one array runs out. The main loop needs two fronts, so it stops as soon as either index reaches the end of its array. Whatever is left in the other array is already sorted, and every value in it is at least as large as everything we have written, so we copy it straight across with no comparisons. Forgetting these leftover loops is the most common bug here, and it is tempting because the main loop looks complete; on our example it would lose the 9.

The variant interviewers often ask next is harder, so let us take it slowly. Suppose a is [2, 6, 10, 0, 0], three real values and two spare slots, and we must merge b = [1, 8] into it without a new array. If we merge from the front, the first value we write, the 1, lands on a's 2, which we have not read yet, and the 2 is lost. The cure is to merge from the back. The largest values go at the end, and the end of a is empty, so we compare the largest unused values, a[i] and b[j], and write the larger into the last free slot k, moving all indexes leftwards.

Step throughThe in-place variant: merging [1, 8] into the back of [2, 6, 10, _, _]

The array is a, with its two spare slots at the end. Filled slots on the right are final. i reads a, k is where the next value is written.

  1. 20611020304ik
    b
    [1, 8]
    j (reads b)
    1
    b[j]
    8
    i
    2
    k
    4

    1a holds 2, 6, 10 and two spare zeros, and b holds 1, 8. i is on the last real value of a, and k is on the last free slot.

  2. 206110203104ik
    b
    [1, 8]
    j (reads b)
    1
    b[j]
    8
    i
    1
    k
    3

    210 is larger than b's 8, so 10 is written into slot 4. It moved into a spare slot, so nothing unread was lost.

  3. 206110283104ik
    b
    [1, 8]
    j (reads b)
    0
    b[j]
    1
    i
    1
    k
    2

    36 is not larger than 8, so 8 from b goes into slot 3. j now points to the 1, the last value left in b.

  4. 20616283104ik
    b
    [1, 8]
    j (reads b)
    0
    b[j]
    1
    i
    0
    k
    1

    46 is larger than 1, so 6 is copied into slot 2. The old 10 there was already copied, so overwriting it is safe.

  5. 20216283104k
    b
    [1, 8]
    j (reads b)
    0
    b[j]
    1
    i
    -1
    k
    0

    52 is larger than 1, so 2 moves into slot 1. i falls to -1, which means every real value of a has been placed.

  6. 10216283104
    b
    [1, 8]
    j (reads b)
    -1
    b[j]
    used up
    i
    -1
    k
    -1

    6Only b's 1 is left, so the else branch writes it into slot 0 and j becomes -1. The loop ends with [1, 2, 6, 8, 10].

Why does merging from the back never overwrite a value we still need? The slot k we write to is always to the right of i, because k starts b.length slots to the right of i and the gap only shrinks when a value of b is written, so k can only catch up with i once b is used up. When b runs out, the values of a that remain already sit in their final places, which is why the loop only watches j.

5Watching the merge on the example

The picture below plays the merge on a = [1, 4, 7, 9] and b = [2, 4, 8]. The top row is a, the middle row is b and the bottom row is the output. The two values being compared are marked, values already copied fade out, and the newest value written to the output is highlighted. The panel shows the three indexes and the two fronts.

As you step through, notice that in every frame exactly one of i and j moves, together with k. The one that stays belongs to the value that lost the comparison, still in play.

Step throughMerging [1, 4, 7, 9] with [2, 4, 8], one copy at a time

Rows are a, b and out. The two compared values are marked, used values fade, and the newest value in out is highlighted.

  1. 1479248
    i (reads a)
    0
    j (reads b)
    0
    k (writes out)
    0
    a[i]
    1
    b[j]
    2

    1We start with i, j and k all at 0. The two values in play are a[0] = 1 and b[0] = 2, the smallest unused value of each array.

  2. 14792481
    i (reads a)
    1
    j (reads b)
    0
    k (writes out)
    1
    a[i]
    4
    b[j]
    2

    21 is smaller than 2, so out[0] gets 1 from a. i moves to 1 and k to 1, while j stays where it was, still on the 2.

  3. 147924812
    i (reads a)
    1
    j (reads b)
    1
    k (writes out)
    2
    a[i]
    4
    b[j]
    4

    3Now 4 meets 2. The 2 from b is smaller, so it goes to out[1] and only j moves on. The 4 in a simply waits its turn.

  4. 1479248124
    i (reads a)
    2
    j (reads b)
    1
    k (writes out)
    3
    a[i]
    7
    b[j]
    4

    44 meets 4, a tie. The test a[i] <= b[j] is true, so we take the 4 from a first. That choice keeps equal values in their original order.

  5. 14792481244
    i (reads a)
    2
    j (reads b)
    2
    k (writes out)
    4
    a[i]
    7
    b[j]
    8

    57 meets the 4 left in b. The 4 is smaller, so out[3] gets it and j moves to 2. Both 4s are now in the answer.

  6. 147924812447
    i (reads a)
    3
    j (reads b)
    2
    k (writes out)
    5
    a[i]
    9
    b[j]
    8

    67 meets 8. The 7 is smaller, so it goes to out[4] from a and i moves to 3, onto the last value of a.

  7. 1479248124478
    i (reads a)
    3
    j (reads b)
    3
    k (writes out)
    6
    a[i]
    9
    b[j]
    used up

    79 meets 8. The 8 goes to out[5] and j becomes 3, past the end of b, so the main loop stops because b is used up.

  8. 14792481244789
    i (reads a)
    4
    j (reads b)
    3
    k (writes out)
    7
    a[i]
    used up
    b[j]
    used up

    8Only 9 is left in a. The leftover loop copies it to out[6] without any comparison, and all seven values are merged in order.

Let us read the important frames back. In the third frame the 2 from b wins and only j moves, while a's 4 waits. The fourth is the tie, settled in favour of a by the <= test, and the fifth copies b's 4 straight after it, so the two 4s keep the order they started in.

The seventh frame is worth a pause. After the 8 is copied, j equals 3, the length of b, so j < b.length is false and the main loop ends with the 9 still unwritten. The last frame is the leftover loop doing its small but essential job.

6The complete Java program

Here is the full class, with the merge into a new array, the in-place merge from the back, and a main that runs our example, an empty first array and the in-place variant. Each trailing comment shows what that line prints.

Java
import java.util.Arrays;
public class MergeArrays {
// Two pointers, one per input: the smaller front value goes next into the result.
static int[] merge(int[] a, int[] b) {
int[] out = new int[a.length + b.length];
int i = 0, j = 0, k = 0; // i reads a, j reads b, k writes out
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) out[k++] = a[i++]; // <= takes ties from a, which keeps it stable
else out[k++] = b[j++];
}
while (i < a.length) out[k++] = a[i++]; // copy whatever is left in a
while (j < b.length) out[k++] = b[j++]; // or in b; only one of these loops runs
return out;
}
// In place variant: a holds m real values, then exactly b.length spare slots.
static void mergeInto(int[] a, int m, int[] b) {
int i = m - 1, j = b.length - 1, k = m + b.length - 1;
while (j >= 0) { // fill from the back, largest first
if (i >= 0 && a[i] > b[j]) a[k--] = a[i--];
else a[k--] = b[j--];
}
}
public static void main(String[] args) {
int[] a = {1, 4, 7, 9}, b = {2, 4, 8};
System.out.println(Arrays.toString(merge(a, b))); // [1, 2, 4, 4, 7, 8, 9]
System.out.println(Arrays.toString(merge(new int[] {}, new int[] {3, 5}))); // [3, 5]
int[] room = {2, 6, 10, 0, 0}; // 3 real values, 2 spare slots
mergeInto(room, 3, new int[] {1, 8});
System.out.println(Arrays.toString(room)); // [1, 2, 6, 8, 10]
}
}

Let us read merge in the order it runs. It creates out with a.length + b.length slots, and i, j and k start at 0. The while loop runs only while both arrays still have a front, because the comparison needs two values.

Inside the loop, out[k++] = a[i++] copies a[i] into out[k] and then adds one to both k and i, because ++ written after a variable means use the current value first and increase it afterwards. Writing the three steps on separate lines means exactly the same. The test a[i] <= b[j] is where the tie rule lives.

After the main loop, two small loops copy the leftovers. If a still has values, the first loop copies them; if b does, the second does. Then we return out, and main prints [1, 2, 4, 4, 7, 8, 9] for our example and [3, 5] when a is empty, since the main loop never runs and the second leftover loop copies b.

mergeInto starts i on the last real value of a, j on the last value of b, and k on the last slot. Each step writes the larger of a[i] and b[j] into a[k] and moves the matching indexes left. The check i >= 0 comes first, so once a's real values are placed the code never reads a[-1] and takes from b instead. main prints [1, 2, 6, 8, 10].

7How much it costs, and the cases at the edges

Let us count on the example first. Seven values were written into the output, each exactly once, and each write needed at most one comparison, six comparisons in all. For arrays of lengths n and m that is n + m writes and fewer than n + m comparisons, so the time is O(n + m). No method can do better, since every value must be copied once.

The new array has n + m slots, so the space is O(n + m), which any method returning a new array must pay. The in-place version uses only three index variables, so its extra space is O(1), read as constant: the same three integers for five values or five million.

Comparing the ways to merge
ApproachTimeExtra space
Join both arrays and sort (brute force)O((n + m) log(n + m))O(n + m)
Two pointers into a new arrayO(n + m)O(n + m) for the output
Two pointers from the back, in placeO(n + m)O(1)

The edge cases are handled without special code, and it is worth seeing why. If a is empty, the main loop never runs, because i < a.length is false at once, and the second leftover loop copies all of b. If both are empty, nothing runs and we return an empty array. Duplicates are all kept, and ties come from a first.

For the in-place version, if every value of b is smaller than all of a, each comparison takes from a until i falls below 0, and then b fills the front. If b is empty, j starts at -1 and the loop never runs, which is correct. The one assumption to state aloud is that a really has b.length spare slots.

8Follow-up questions

How would you merge k sorted arrays instead of two?

Comparing every front at each step costs k comparisons per value. Instead we put the first value of each array into a min-heap, which always gives back its smallest entry, together with the array and position it came from. We repeatedly take the smallest out, append it, and put in the next value from the same array. With N values in total, each one enters and leaves the heap once at a cost of O(log k), so the whole merge is O(N log k) time with O(k) extra space besides the output.

Why not merge from the front in the in-place version and shift values to make room?

It works, but each value of b that goes before values of a forces every remaining value of a one place to the right, up to n moves for each of the m values, so O(n times m) in the worst case. Filling from the back avoids all shifting, because the slots at the end are empty and the largest values belong there, so each value moves exactly once.

9Conclusion

We merged two sorted arrays by keeping one index in each, copying the smaller front into the output, and copying the leftovers when one array ran out. Each value is written once, so it takes O(n + m) time, and taking ties from the first array keeps the merge stable. When the first array has room at its end, filling from the back merges in place with O(1) extra space. The clue to remember is two sorted inputs that must be combined: the smallest unused value is always one of the two fronts, so walk both with one forward index each.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the setup: both arrays are sorted ascending, duplicates are kept, and I return a new array; I will also ask about the in-place version. Joining and sorting works but costs O((n plus m) log(n plus m)) and ignores the order I was given.

Then, if they want more

Since each array is sorted, the smallest unused value overall is always the front of one of them, so this is a two pointer merge. I keep i in a, j in b and k in the output. While both have values left, I copy the smaller of a[i] and b[j] to out[k] and move that index and k forward.

On a tie I take from a, so the merge is stable. Then I copy whatever is left of the other array. Every value is written once, so it is O(n plus m) time, plus the output array.

For the in-place version, merging from the front would overwrite unread values of a, so I merge from the back: compare the largest unused values and write the larger into the last free slot, moving left, until b is used up. That is O(n plus m) time and O(1) extra space.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 47 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Merge two sorted arrays into one sorted array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/merge-two-sorted-arrays-into-one-sorted-array-160cca/