710059. Find pairs with given sum in doubly linked list

Easy

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:

  1. Initialize two pointers, slow and fast, to point to the head of the list.
  2. Calculate the sum of the first node (head) and store it in a variable total_sum.
  3. Move the fast pointer one step ahead until the total sum exceeds the target sum.
  4. Move the slow pointer one step ahead when the total sum equals the target sum.
  5. 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_sum variable by subtracting the value at the node pointed to by the slow pointer.
  6. Repeat steps 3-5 until the fast pointer 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

View on GeeksforGeeks
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;
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.