VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-pairs-given-sum-doubly-linked-list/

⇱ Find pairs with given sum in doubly linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find pairs with given sum in doubly linked list

Last Updated : 23 Jul, 2025

Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to the given value x in sorted order.

Examples:

Input:

👁 Find-pairs-with-given-sum-in-doubly-linked-list


Output: (1, 6), (2,5)
Explanation: We can see that there are two pairs (1, 6) and (2, 5) with sum 7.

Input:

👁 Find-pairs-with-given-sum-in-doubly-linked-list-2


Output: (1,5)
Explanation: We can see that there is one pair (1, 5) with a sum of 6.

[Naive Approach] Using Hashing - O(nlogn) Time and O(n) Space

This approach finds pairs of nodes in a doubly linked list that sum up to a given target. It uses a hash map to track the values of nodes as the list is traversed. For each node, it calculates the complement (target - node value) and checks if it exists in the map. If found, a valid pair is stored. After traversal, the pairs are sorted to maintain the order.


Output
2 5

[Expected Approach] Using Two Pointer Technique - O(n) Time and O(1) Space

The idea is to use two pointers, one starting at the head and the other at the end of the sorted doubly linked list. Move the first pointer forward if the sum of the two pointer's values is less than the target, or move the second pointer backward if the sum is greater. Continue until the pointers meet or cross each other.

An efficient solution for this problem is the same as Pair with given Sum (Two Sum) article.  

  • Initialize two pointer variables to find the candidate elements in the sorted doubly linked list. Initialize first with the start of the doubly linked list and second with the last node.
  • If current sum of first and second is less than x, then we move first in forward direction. If current sum of first and second element is greater than x, then we move second in backward direction.
  • The loop terminates when two pointers cross each other (second->next = first), or they become the same (first == second).

Output
2 5
Comment
Article Tags: