Merge Two Sorted Lists
Easy linked-list · two-pointers
Description
Constraints
0 <= n, m <= 100000
Examples
Input: a = [1,2,4], b = [1,3,4]
Output: [1,1,2,3,4,4]
Hints (1)
- Advance two pointers, always taking the smaller head.
Solutions
Two-pointer merge. · Time O(n+m) · Space O(n+m)
func mergeSorted(a, b []int) []int {
out := []int{}
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
out = append(out, a[i]); i++
} else {
out = append(out, b[j]); j++
}
}
out = append(out, a[i:]...)
out = append(out, b[j:]...)
return out
}
Two-pointer merge. · Time O(n+m) · Space O(n+m)
function mergeSorted(a, b) {
const out = []; let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
while (i < a.length) out.push(a[i++]);
while (j < b.length) out.push(b[j++]);
return out;
}
Two-pointer merge. · Time O(n+m) · Space O(n+m)
function mergeSorted($a, $b) {
$out = []; $i = 0; $j = 0;
while ($i < count($a) && $j < count($b)) {
if ($a[$i] <= $b[$j]) { $out[] = $a[$i++]; } else { $out[] = $b[$j++]; }
}
while ($i < count($a)) { $out[] = $a[$i++]; }
while ($j < count($b)) { $out[] = $b[$j++]; }
return $out;
}
Two-pointer merge. · Time O(n+m) · Space O(n+m)
def mergeSorted(a, b):
out = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:])
out.extend(b[j:])
return out
Two-pointer merge. · Time O(n+m) · Space O(n+m)
function mergeSorted(a: number[], b: number[]): number[] {
const out: number[] = []; let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
while (i < a.length) out.push(a[i++]);
while (j < b.length) out.push(b[j++]);
return out;
}
Create a free account to submit solutions, track progress and save problems.
Create account