710059. Find pairs with given sum in doubly linked list
Find pairs with given sum in doubly linked list
Summary
Find all pairs of nodes in a doubly linked list that have a sum equal to a given target sum. This problem is about traversing and manipulating a doubly linked list using a two-pointer algorithm.
Detailed Explanation
To solve this problem, we can use a two-pointer approach where one pointer moves ahead and the other stays behind. The idea is to maintain a window of nodes in the list such that the sum of all nodes in the window equals the target sum. We start by initializing the two pointers at the beginning of the list.
Here's the step-by-step breakdown:
- Initialize two pointers,
slowandfast, to point to the head of the list. - Calculate the sum of the first node (
head) and store it in a variabletotal_sum. - Move the
fastpointer one step ahead until the total sum exceeds the target sum. - Move the
slowpointer one step ahead when the total sum equals the target sum. - If the total sum is equal to the target sum, it means we have found a pair of nodes with a sum equal to the target sum. Print or store this pair and update the
total_sumvariable by subtracting the value at the node pointed to by theslowpointer. - Repeat steps 3-5 until the
fastpointer reaches the end of the list.
Time complexity: O(n), where n is the number of nodes in the doubly linked list. We only traverse the list once, and each operation takes constant time.
Space complexity: O(1), as we only use a few extra variables to store the pointers and sum.
Optimized Solutions
Java
public class Node {
int val;
Node prev, next;
public Node(int val) {
this.val = val;
}
}
public void findPairs(Node head, int targetSum) {
Node slow = head, fast = head;
int totalSum = 0;
while (fast != null && fast.next != null) {
if (totalSum + fast.next.val > targetSum) {
fast = fast.next;
} else {
totalSum += fast.val;
if (totalSum == targetSum) {
System.out.println("Pair found: " + slow.val + ", " + fast.next.val);
totalSum -= slow.val;
slow = slow.next;
}
}
}
}