Merge two sorted lists in linear time.
Every value taken so far is no larger than any value still waiting in either list, and the taken values are in order.
Use it when two lists are already sorted and you need one ordered list, or a question about both lists at once. Signal words: two sorted lists, already in order, merge, in common, overlap, both lists.
Start: one pointer at the front of each list, and an empty answer.
Step: compare the two fronts. Take the smaller and move only its pointer. Equal fronts: a merge takes one and keeps the other for the next step; a shared-values search keeps one and moves both pointers.
Stop: when either list runs out. A merge then copies the rest of the other list; a shared-values search stops, because nothing more can match.
It does not work on lists that are not sorted. Sort them first, or use a hash set.
Cost: each step moves a pointer forward by at least one, so at most n + m steps: O(n + m) time, and O(n + m) space for the new list.
def merge_sorted(first, second):
# [1] One pointer at the front of each list; the merged list is empty.
merged = []
i = 0
j = 0
# [2] While both lists have values left, compare their front values.
while i < len(first) and j < len(second):
# [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if first[i] <= second[j]:
merged.append(first[i])
i += 1
# [4] The front of second is smaller: take it.
else:
merged.append(second[j])
j += 1
# [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while i < len(first):
merged.append(first[i])
i += 1
while j < len(second):
merged.append(second[j])
j += 1
# [6] Report the merged list, in order.
return mergedpublic int[] mergeSorted(int[] first, int[] second) {
// [1] One pointer at the front of each list; the merged list is empty.
int[] merged = new int[first.length + second.length];
int size = 0;
int i = 0;
int j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged[size++] = first[i];
i++;
}
// [4] The front of second is smaller: take it.
else {
merged[size++] = second[j];
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.length) {
merged[size++] = first[i];
i++;
}
while (j < second.length) {
merged[size++] = second[j];
j++;
}
// [6] Report the merged list, in order.
return merged;
}vector<int> mergeSorted(vector<int>& first, vector<int>& second) {
// [1] One pointer at the front of each list; the merged list is empty.
vector<int> merged;
size_t i = 0;
size_t j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.size() && j < second.size()) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged.push_back(first[i]);
i++;
}
// [4] The front of second is smaller: take it.
else {
merged.push_back(second[j]);
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.size()) {
merged.push_back(first[i]);
i++;
}
while (j < second.size()) {
merged.push_back(second[j]);
j++;
}
// [6] Report the merged list, in order.
return merged;
}function mergeSorted(first, second) {
// [1] One pointer at the front of each list; the merged list is empty.
const merged = [];
let i = 0;
let j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged.push(first[i]);
i++;
}
// [4] The front of second is smaller: take it.
else {
merged.push(second[j]);
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.length) {
merged.push(first[i]);
i++;
}
while (j < second.length) {
merged.push(second[j]);
j++;
}
// [6] Report the merged list, in order.
return merged;
}def shared_values(first, second):
# [1] One pointer at the front of each list; no shared value found yet.
shared = []
i = 0
j = 0
# [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while i < len(first) and j < len(second):
# [3] The front of first is smaller: every value left in second is larger, so it has no match.
if first[i] < second[j]:
i += 1
# [4] The front of second is smaller: it has no match, for the same reason.
elif second[j] < first[i]:
j += 1
# [5] The fronts are equal: keep the value once, and advance both pointers.
else:
shared.append(first[i])
i += 1
j += 1
# [6] Shared values were found from the smallest up, so they are already in order.
return sharedpublic int[] sharedValues(int[] first, int[] second) {
// [1] One pointer at the front of each list; no shared value found yet.
int[] shared = new int[Math.min(first.length, second.length)];
int size = 0;
int i = 0;
int j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared[size++] = first[i];
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return java.util.Arrays.copyOf(shared, size);
}vector<int> sharedValues(vector<int>& first, vector<int>& second) {
// [1] One pointer at the front of each list; no shared value found yet.
vector<int> shared;
size_t i = 0;
size_t j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.size() && j < second.size()) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared.push_back(first[i]);
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return shared;
}function sharedValues(first, second) {
// [1] One pointer at the front of each list; no shared value found yet.
const shared = [];
let i = 0;
let j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared.push(first[i]);
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return shared;
}while i < len(first) and j < len(second):
...
return merged # bug: one list may still hold valuesThis version treats equal fronts like the shared-values template: it takes one value and moves both pointers.
A tempting shortcut is to run the merge on a list from a gate whose clock was wrong, so its scans are not in order.
Your team lead brings a request from the support team. They want the parcel ids that appear in both of two lists of complaints. The lists arrive in no order, for example [9, 4, 7] and [7, 1, 9].
systemdesignmastery.dev/dsa/cheatsheets/merging-sorted-sequences