Merge two sorted arrays
Combine two sorted integer arrays into one sorted array without sorting the result afterward.
Course progress
Problem 28 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
first = [1, 4, 7]; second = [2, 3, 8]
Expected output
1 2 3 4 7 8
What is happening?
Compare the front values of both sorted arrays and repeatedly take the smaller one, producing one sorted result.
Solution strategy
Build the right mental model
Compare the next unused item in each array, append the smaller one, then copy any remaining tail.
Core concepts
two pointers · arrays
Complexity
Time O(n + m), space O(n + m) for the result.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for merge-sorted-arrays
using System;
class Program
{
static int[] Merge(int[] first, int[] second)
{
int[] result = new int[first.Length + second.Length];
int i = 0, j = 0, write = 0;
while (i < first.Length && j < second.Length)
result[write++] = first[i] <= second[j] ? first[i++] : second[j++];
while (i < first.Length) result[write++] = first[i++];
while (j < second.Length) result[write++] = second[j++];
return result;
}
static void Main()
{
Console.WriteLine(string.Join(" ", Merge(new[] { 1, 4, 7 }, new[] { 2, 3, 8 })));
}
}Knowledge check
Questions students often ask
What is the main idea behind merge two sorted arrays?
Compare the next unused item in each array, append the smaller one, then copy any remaining tail.
What is the time and space complexity of this solution?
Time O(n + m), space O(n + m) for the result.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.