Merging two sorted arrays
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Copying two sorted arrays of lengths n and m into one array and calling Arrays.sort takes O((n + m) log(n + m)) time and ignores the fact that both inputs are already sorted. Using one pointer per array merges them in a single O(n + m) pass.
Merging into a new array
Merging is combining two sorted lists into one sorted list by repeatedly taking the smaller of the two front elements.
Merging two sorted arrays a (length n) and b (length m) builds one sorted array from both. Allocate int[] merged = new int[n + m] and keep three pointers: i = 0 in a, j = 0 in b, and k = 0 in merged.
import java.util.Arrays;
public class MergeTwo { public static void main(String[] args) { int[] a = {1, 4, 7}, b = {2, 3, 9}; int[] merged = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) merged[k++] = a[i] <= b[j] ? a[i++] : b[j++]; while (i < a.length) merged[k++] = a[i++]; // tail of a while (j < b.length) merged[k++] = b[j++]; // tail of b System.out.println(Arrays.toString(merged)); }}[1, 2, 3, 4, 7, 9]
While both arrays still have elements left (while (i < n && j < m)), compare a[i] and b[j] and copy the smaller (or equal) element into merged[k++]. When one array runs out of elements, the main loop ends — and you run two short cleanup loops (while (i < n) and while (j < m)) to copy whichever tail remains. Only one of the two cleanup loops will execute at least one step.
- Set
i = 0,j = 0, andk = 0. - While
i < a.length && j < b.length, copya[i] <= b[j] ? a[i++] : b[j++]tomerged[k++]. - Copy any remaining elements from
a(while (i < a.length) merged[k++] = a[i++];). - Copy any remaining elements from
b(while (j < b.length) merged[k++] = b[j++];).
Merging in place from the end
In (Merge Sorted Array), nums1 has length m + n, where the first m slots hold sorted elements and the last n slots are empty (0s) reserved to hold the n elements of nums2.
Example 1 · Brute force: copy nums2 behind nums1, then sort (O((m + n) log (m + n)) time, O(1) extra space)
import java.util.Arrays;
public class MergeBrute { public static void merge(int[] nums1, int m, int[] nums2, int n) { for (int j = 0; j < n; j++) { nums1[m + j] = nums2[j]; } Arrays.sort(nums1); }
public static void main(String[] args) { int[] nums1 = {1, 3, 5, 0, 0, 0}; int[] nums2 = {2, 4, 6}; merge(nums1, 3, nums2, 3); System.out.println("Merged by sorting: " + Arrays.toString(nums1)); }}Merged by sorting: [1, 2, 3, 4, 5, 6]
What this code does
- Both halves are already sorted, yet
Arrays.sortstarts from scratch and pays O((m + n) log (m + n)). - Filling
nums1from the back with the larger of the two current values uses the sorted order and finishes in one O(m + n) pass.
Example 2 · Optimal: merge in place from the back (O(m + n) time, O(1) space)
import java.util.Arrays;
public class MergeInPlaceDemo { public static void mergeInPlace(int[] nums1, int m, int[] nums2, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1;
while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { nums1[k--] = nums1[i--]; } else { nums1[k--] = nums2[j--]; } } }
public static void main(String[] args) { int[] nums1 = {1, 3, 5, 0, 0, 0}; int[] nums2 = {2, 4, 6}; mergeInPlace(nums1, 3, nums2, 3); System.out.println("Merged in place: " + Arrays.toString(nums1)); }}Merged in place: [1, 2, 3, 4, 5, 6]
What this code does
- Starting
kat the empty tail (m + n - 1) guarantees thatk >= iat every step, sonums1[i]is never overwritten before it is read. - The loop condition
while (j >= 0)handles both the main comparison (wheni >= 0) and copying any remainingnums2elements (wheni < 0). - Why it is faster: each value is placed once, in its final slot, by one comparison. Nothing is re-sorted.
If you try to merge from the front (k = 0), writing an element from nums2 into nums1[0] immediately overwrites nums1[0] before it has been placed!
The solution is to merge from the back:
i = m - 1(last valid element ofnums1)j = n - 1(last element ofnums2)k = m + n - 1(last slot ofnums1)
At each step while j >= 0, compare nums1[i] (if i >= 0) with nums2[j] and place the larger value into nums1[k--]. Once j < 0, all of nums2 is placed and any remaining nums1[0..i] elements are already sitting in their final sorted positions!
Order of execution
Order one merge step
Tap the steps in the order one loop pass runs them.
nums2 into the back of nums1, you only need a cleanup loop for j >= 0; any leftover elements in nums1[0..i] are already in place.Intersection, union, and real-world sorted log merging
Two pointers across two sorted arrays also compute set operations in O(n + m) time without hashing.
Example 3 · Unique intersection and union of two sorted arrays
import java.util.ArrayList;import java.util.List;
public class SortedSetOpsDemo { public static List<Integer> intersection(int[] a, int[] b) { List<Integer> res = new ArrayList<>(); int i = 0, j = 0; while (i < a.length && j < b.length) { if (a[i] < b[j]) { i++; } else if (a[i] > b[j]) { j++; } else { if (res.isEmpty() || res.get(res.size() - 1) != a[i]) { res.add(a[i]); } i++; j++; } } return res; }
public static List<Integer> union(int[] a, int[] b) { List<Integer> res = new ArrayList<>(); int i = 0, j = 0; while (i < a.length || j < b.length) { int val; if (i < a.length && (j >= b.length || a[i] <= b[j])) { val = a[i++]; } else { val = b[j++]; } if (res.isEmpty() || res.get(res.size() - 1) != val) { res.add(val); } } return res; }
public static void main(String[] args) { int[] a = {1, 2, 2, 4, 6}; int[] b = {2, 2, 3, 4, 7}; System.out.println("Intersection: " + intersection(a, b)); System.out.println("Union: " + union(a, b)); }}Intersection: [2, 4] Union: [1, 2, 3, 4, 6, 7]
What this code does
- Checking
res.isEmpty() || res.get(res.size() - 1) != valdeduplicates the sorted output in O(1) time without needing aHashSet. - Both methods finish in O(a.length + b.length) time and O(1) auxiliary working space.
Example 4 · Real world: merging two timestamped server log streams
import java.util.ArrayList;import java.util.List;
public class LogMergerDemo { static class LogEntry { final long timestampMs; final String server; final String message;
LogEntry(long timestampMs, String server, String message) { this.timestampMs = timestampMs; this.server = server; this.message = message; }
@Override public String toString() { return timestampMs + "ms [" + server + "] " + message; } }
public static List<LogEntry> mergeLogs(List<LogEntry> srvA, List<LogEntry> srvB) { List<LogEntry> timeline = new ArrayList<>(srvA.size() + srvB.size()); int i = 0, j = 0; while (i < srvA.size() && j < srvB.size()) { if (srvA.get(i).timestampMs <= srvB.get(j).timestampMs) { timeline.add(srvA.get(i++)); } else { timeline.add(srvB.get(j++)); } } while (i < srvA.size()) timeline.add(srvA.get(i++)); while (j < srvB.size()) timeline.add(srvB.get(j++)); return timeline; }
public static void main(String[] args) { List<LogEntry> web1 = List.of( new LogEntry(100, "web-1", "GET /login"), new LogEntry(150, "web-1", "POST /auth") ); List<LogEntry> web2 = List.of( new LogEntry(120, "web-2", "GET /home"), new LogEntry(180, "web-2", "GET /profile") ); for (LogEntry entry : mergeLogs(web1, web2)) { System.out.println(entry); } }}100ms [web-1] GET /login 120ms [web-2] GET /home 150ms [web-1] POST /auth 180ms [web-2] GET /profile
What this code does
- Using
<=when comparingsrvA.get(i).timestampMs <= srvB.get(j).timestampMsmakes the merge stable: if both servers log at the same millisecond,srvAentries appear first in their original order. - Each log entry is inspected once, producing a unified chronological log in O(n + m) time.
- Sorted Intersection: While
i < n && j < m, ifa[i] < b[j]doi++; ifa[i] > b[j]doj++; ifa[i] == b[j], adda[i](if it differs from the last added element to avoid duplicates) and advance bothi++andj++. - Sorted Union: Advance the smaller pointer (or both when equal), appending each value only if the result list is empty or its last element differs from the new value.
Real world — merging sorted log files: In distributed systems (and inside Merge Sort and LSM-tree databases like RocksDB and Cassandra), each web server writes log lines ordered by timestamp. To build a single chronological timeline across servers without loading gigabytes into memory to sort, a log aggregator reads the next line from each stream and always emits the one with the earlier timestamp.
- Intersection: record only when
a[i] == b[j]. - Union: record smaller of
a[i]andb[j](and advance both on a tie), skipping duplicates. - Log aggregation: merge streams by timestamp in O(n + m) time and O(1) working memory per stream.
Next step
Check your understanding
10 quick questions