Find pairs with a given sum in a DLL
Pattern: Doubly and circular lists
The list is sorted, so use two pointers from both ends, as for an array. A small sum moves the left pointer forward, a big sum moves the right pointer back through prev.
The problem
Given the head of a sorted doubly linked list of different positive whole numbers and a target, return every pair of
values that adds up to the target, each pair smaller value first, in increasing order of the smaller value. For example,
1 ⇄ 2 ⇄ 4 ⇄ 5 ⇄ 6 ⇄ 8 ⇄ 9 with target 7 gives [[1, 6], [2, 5]].
The link above is a GeeksforGeeks article. The function name findPairsWithGivenSum is this guide's own. In this
guide's code the node type is DNode.
Think first
- How would you solve this on a sorted array?
- Which pointer lets the right end move backwards?
- When should the walk stop?
Hints
Brute force, and why it fails
Check every pair: O(n²). A hash set of values is O(n) time with O(n) memory. Two pointers are O(n) time and O(1) memory.
The key insight
Sorted order plus a way to walk backwards is all the two-pointer method needs. The prev pointer supplies the backwards
step that a singly linked list lacks.
Dry run
The list is 1 ⇄ 2 ⇄ 4 ⇄ 5 ⇄ 6 ⇄ 8 ⇄ 9 and the target is 7. left starts on 1 and right on 9.
The plan
left = head, right = tail
while left != right and right.next != left:
s = left.val + right.val
if s == target: record (left.val, right.val); left = left.next; right = right.prev
else if s < target: left = left.next
else: right = right.prev
Complexity
- Time
O(n)- Space
O(1)
Each step moves at least one pointer. The list of pairs is the output.
Edge cases
- No pair: an empty list.
- One node: no pairs.
- The pair is the head and the tail: found in the first step.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<int[]> findPairsWithGivenSum(DNode head, int target) {
List<int[]> out = new ArrayList<>();
if (head == null) return out;
DNode left = head, right = head;
while (right.next != null) right = right.next; // two ends of the sorted list
while (left != right && right.next != left) { // stop when they meet or cross
int sum = left.val + right.val;
if (sum == target) {
out.add(new int[]{left.val, right.val});
left = left.next;
right = right.prev;
} else if (sum < target) {
left = left.next; // need a bigger sum
} else {
right = right.prev; // need a smaller sum
}
}
return out;
}
}C++
class Solution {
public:
vector<vector<int>> findPairsWithGivenSum(DNode* head, int target) {
vector<vector<int>> out;
if (head == NULL) return out;
DNode *left = head, *right = head;
while (right->next != NULL) right = right->next; // two ends of the sorted list
while (left != right && right->next != left) { // stop when they meet or cross
int sum = left->val + right->val;
if (sum == target) {
out.push_back({left->val, right->val});
left = left->next;
right = right->prev;
} else if (sum < target) {
left = left->next; // need a bigger sum
} else {
right = right->prev; // need a smaller sum
}
}
return out;
}
};Python
from lib import DNode
class Solution:
def findPairsWithGivenSum(self, head: DNode, target: int) -> list[list[int]]:
out = []
if head is None:
return out
left = right = head
while right.next is not None: # two ends of the sorted list
right = right.next
while left is not right and right.next is not left: # stop when they meet or cross
total = left.val + right.val
if total == target:
out.append([left.val, right.val])
left, right = left.next, right.prev
elif total < target:
left = left.next # need a bigger sum
else:
right = right.prev # need a smaller sum
return outCommon mistakes
- Stopping only on
left == right, which misses the crossing case for even lengths. - Moving only one pointer after a match, which can report the same value twice.
- Forgetting to find the tail first.