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:
Output: (1, 6), (2,5)
Explanation: We can see that there are two pairs (1, 6) and (2, 5) with sum 7.
Input:
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.
C++
// C++ program to find a pair with given sum x
// using map
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int value) {
data = value;
next = nullptr;
}
};
// Function to find pairs in the doubly linked list
// whose sum equals the given value x
vector<pair<int, int>> findPairsWithGivenSum(Node *head, int target) {
vector<pair<int, int>> ans;
unordered_map<int, Node *> visited;
Node *currNode = head;
// Traverse the doubly linked list
while (currNode != nullptr) {
int x = target - currNode->data;
// Check if the target exists in the map
if (visited.find(x) != visited.end()) {
// Pair found
ans.push_back({x, currNode->data});
}
// Store the current node's value in the map
visited[currNode->data] = currNode;
currNode = currNode->next;
}
sort(ans.begin(), ans.end());
return ans;
}
int main() {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node *head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(4);
head->next->next->next = new Node(5);
int target = 7;
vector<pair<int, int>> pairs = findPairsWithGivenSum(head, target);
if (pairs.empty()) {
cout << "No pairs found." << endl;
}
else {
for (auto &pair : pairs) {
cout << pair.first << " " << pair.second << endl;
}
}
return 0;
}
Java
// Java program to find a pair with given sum x
// using map
import java.util.*;
class Node {
int data;
Node next;
Node(int value) {
data = value;
next = null;
}
}
class GfG {
static ArrayList<ArrayList<Integer> >
findPairsWithGivenSum(int target, Node head) {
ArrayList<ArrayList<Integer> > ans
= new ArrayList<>();
HashSet<Integer> visited = new HashSet<>();
Node currNode = head;
// Traverse the doubly linked list
while (currNode != null) {
int x = target - currNode.data;
// Check if the target exists in the visited set
if (visited.contains(x)) {
// Pair found, add it to the answer
ArrayList<Integer> pair = new ArrayList<>();
pair.add(x);
pair.add(currNode.data);
ans.add(pair);
}
// Add the current node's value to the visited
// set
visited.add(currNode.data);
currNode = currNode.next;
}
// Sort the pairs by the first element of the pair
Collections.sort(
ans, (a, b) -> a.get(0).compareTo(b.get(0)));
return ans;
}
public static void main(String[] args) {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
int target = 7;
ArrayList<ArrayList<Integer> > pairs
= findPairsWithGivenSum(target, head);
if (pairs.isEmpty()) {
System.out.println("No pairs found.");
}
else {
for (ArrayList<Integer> pair : pairs) {
System.out.println(pair.get(0) + " "
+ pair.get(1));
}
}
}
}
Python
# Python program to find a pair with given sum x
# using map
class Node:
def __init__(self, value):
self.data = value
self.next = None
def findPairsWithGivenSum(target, head):
ans = []
visited = set()
currNode = head
# Traverse the doubly linked list
while currNode is not None:
x = target - currNode.data
# Check if the target exists in the visited set
if x in visited:
# Pair found, add it to the answer
ans.append([x, currNode.data])
# Add the current node's value to the visited set
visited.add(currNode.data)
currNode = currNode.next
# Sort the pairs by the first element of the pair
ans.sort(key=lambda pair: pair[0])
return ans
# Helper function to create a linked list
def create_linked_list(values):
head = Node(values[0])
current = head
for value in values[1:]:
current.next = Node(value)
current = current.next
return head
if __name__ == "__main__":
# Create a doubly linked list: 1 -> 2 -> 4 -> 5
values = [1, 2, 4, 5]
head = create_linked_list(values)
target = 7
pairs = findPairsWithGivenSum(target, head)
if not pairs:
print("No pairs found.")
else:
for pair in pairs:
print(pair[0], pair[1])
C#
// C# program to find a pair with given sum x
// using map
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node next;
public Node(int value) {
data = value;
next = null;
}
}
class GfG {
static List<Tuple<int, int>> FindPairsWithGivenSum(Node head, int target) {
List<Tuple<int, int>> ans = new List<Tuple<int, int>>();
HashSet<int> visited = new HashSet<int>();
Node currNode = head;
// Traverse the doubly linked list
while (currNode != null) {
int x = target - currNode.data;
// Check if the target exists in the visited set
if (visited.Contains(x)) {
// Pair found
ans.Add(new Tuple<int, int>(x, currNode.data));
}
// Add the current node's value to the visited set
visited.Add(currNode.data);
currNode = currNode.next;
}
// Sort the pairs
ans.Sort((a, b) => a.Item1.CompareTo(b.Item1));
return ans;
}
static void Main() {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
int target = 7;
List<Tuple<int, int>> pairs = FindPairsWithGivenSum(head, target);
if (pairs.Count == 0) {
Console.WriteLine("No pairs found.");
} else {
foreach (var pair in pairs) {
Console.WriteLine(pair.Item1 + " " + pair.Item2);
}
}
}
}
JavaScript
// JavaScript program to find a pair with given sum x
// using map
class Node {
constructor(value) {
this.data = value;
this.next = null;
}
}
function findPairsWithGivenSum(head, target) {
let ans = [];
let visited = new Set();
let currNode = head;
// Traverse the doubly linked list
while (currNode !== null) {
let x = target - currNode.data;
// Check if the target exists in the visited set
if (visited.has(x)) {
// Pair found
ans.push([ x, currNode.data ]);
}
// Add the current node's value to the visited set
visited.add(currNode.data);
currNode = currNode.next;
}
// Sort the pairs
ans.sort((a, b) => a[0] - b[0]);
return ans;
}
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
let target = 7;
let pairs = findPairsWithGivenSum(head, target);
if (pairs.length === 0) {
console.log("No pairs found.");
}
else {
for (let pair of pairs) {
console.log(pair[0] + " " + pair[1]);
}
}
[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).
C++
// C++ program to find a pair with given sum target.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *next, *prev;
Node(int value) {
data = value;
next = nullptr;
prev = nullptr;
}
};
// Function to find pairs in the doubly
// linked list whose sum equals the given value x
vector<pair<int, int>> findPairsWithGivenSum(Node *head, int target) {
vector<pair<int, int>> res;
// Set two pointers, first to the beginning of DLL
// and second to the end of DLL.
Node *first = head;
Node *second = head;
// Move second to the end of the DLL
while (second->next != nullptr)
second = second->next;
// To track if we find a pair or not
bool found = false;
// The loop terminates when two pointers
// cross each other (second->next == first),
// or they become the same (first == second)
while (first != second && second->next != first) {
// If the sum of the two nodes is equal to x, print the pair
if ((first->data + second->data) == target) {
found = true;
res.push_back({first->data, second->data});
// Move first in forward direction
first = first->next;
// Move second in backward direction
second = second->prev;
}
else {
if ((first->data + second->data) < target)
first = first->next;
else
second = second->prev;
}
}
// If no pair is found
return res;
}
int main() {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node *head = new Node(1);
head->next = new Node(2);
head->next->prev = head;
head->next->next = new Node(4);
head->next->next->prev = head->next;
head->next->next->next = new Node(5);
head->next->next->next->prev = head->next->next;
int target = 7;
vector<pair<int, int>> pairs = findPairsWithGivenSum(head, target);
if (pairs.empty()) {
cout << "No pairs found." << endl;
}
else {
for (auto &pair : pairs) {
cout << pair.first << " " << pair.second << endl;
}
}
return 0;
}
Java
// Java program to find a pair with given sum target.
import java.util.ArrayList;
class Node {
int data;
Node next, prev;
Node(int value) {
data = value;
next = prev = null;
}
}
class GfG {
// Function to find pairs in the doubly linked list
// whose sum equals the given value target
static ArrayList<ArrayList<Integer> >
findPairsWithGivenSum(int target, Node head) {
ArrayList<ArrayList<Integer> > res
= new ArrayList<>();
// Set two pointers, first to the beginning of DLL
// and second to the end of DLL.
Node first = head;
Node second = head;
// Move second to the end of the DLL
while (second.next != null)
second = second.next;
// Iterate through the list using two pointers to
// find pairs
while (first != second && second.next != first) {
// If the sum of the two nodes is equal to
// target, add the pair
if ((first.data + second.data) == target) {
ArrayList<Integer> pair = new ArrayList<>();
pair.add(first.data);
pair.add(second.data);
res.add(pair);
// Move first in forward direction
first = first.next;
// Move second in backward direction
second = second.prev;
}
else {
if ((first.data + second.data) < target)
first = first.next;
else
second = second.prev;
}
}
return res;
}
public static void main(String[] args) {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(4);
head.next.next.prev = head.next;
head.next.next.next = new Node(5);
head.next.next.next.prev = head.next.next;
int target = 7;
ArrayList<ArrayList<Integer> > pairs
= findPairsWithGivenSum(target, head);
if (pairs.isEmpty()) {
System.out.println("No pairs found.");
}
else {
for (ArrayList<Integer> pair : pairs) {
System.out.println(pair.get(0)
+ " " + pair.get(1));
}
}
}
}
Python
# Python program to find a pair with given sum target.
class Node:
def __init__(self, value):
self.data = value
self.next = None
self.prev = None
# Function to find pairs in the doubly linked list
# whose sum equals the given value target
def find_pairs_with_given_sum(head, target):
res = []
# Set two pointers, first to the beginning of DLL
# and second to the end of DLL.
first = head
second = head
# Move second to the end of the DLL
while second.next is not None:
second = second.next
# The loop terminates when two pointers
# cross each other (second.next == first),
# or they become the same (first == second)
while first != second and second.next != first:
if (first.data + second.data) == target:
# Add pair to the result list
res.append((first.data, second.data))
# Move first in forward direction
first = first.next
# Move second in backward direction
second = second.prev
elif (first.data + second.data) < target:
first = first.next
else:
second = second.prev
return res
if __name__ == "__main__":
# Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
head = Node(1)
head.next = Node(2)
head.next.prev = head
head.next.next = Node(4)
head.next.next.prev = head.next
head.next.next.next = Node(5)
head.next.next.next.prev = head.next.next
target = 7
pairs = find_pairs_with_given_sum(head, target)
if not pairs:
print("No pairs found.")
else:
for pair in pairs:
print(pair[0], pair[1])
C#
// C# program to find a pair with given sum target.
using System;
using System.Collections.Generic;
class Node {
public int Data;
public Node Next, Prev;
public Node(int value) {
Data = value;
Next = null;
Prev = null;
}
}
class GfG {
// Function to find pairs in the doubly linked list
// whose sum equals the given value target
static List<Tuple<int, int> >
FindPairsWithGivenSum(Node head, int target) {
List<Tuple<int, int> > result
= new List<Tuple<int, int> >();
Node first = head;
Node second = head;
// Move second pointer to the last node
while (second.Next != null)
second = second.Next;
// Iterate using two pointers to find pairs
while (first != second && second.Next != first) {
if (first.Data + second.Data == target) {
result.Add(
Tuple.Create(first.Data, second.Data));
// Move first in forward direction
first = first.Next;
// Move second in backward direction
second = second.Prev;
}
else if (first.Data + second.Data < target) {
first = first.Next;
}
else {
second = second.Prev;
}
}
return result;
}
static void Main(string[] args) {
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
Node head = new Node(1);
head.Next = new Node(2);
head.Next.Prev = head;
head.Next.Next = new Node(4);
head.Next.Next.Prev = head.Next;
head.Next.Next.Next = new Node(5);
head.Next.Next.Next.Prev = head.Next.Next;
int target = 7;
List<Tuple<int, int> > pairs
= FindPairsWithGivenSum(head, target);
if (pairs.Count == 0) {
Console.WriteLine("No pairs found.");
}
else {
foreach(var pair in pairs) {
Console.WriteLine($"{pair.Item1} {pair.Item2}");
}
}
}
}
JavaScript
// JavaScript program to find a pair with given sum target.
class Node {
constructor(value) {
this.data = value;
this.next = null;
this.prev = null;
}
}
// Function to find pairs in the doubly linked list
// whose sum equals the given value target
function findPairsWithGivenSum(head, target) {
let res = [];
let first = head;
let second = head;
// Move second pointer to the end of the DLL
while (second.next !== null) {
second = second.next;
}
// Iterate through the list using two pointers
while (first !== second && second.next !== first) {
if (first.data + second.data === target) {
res.push([ first.data, second.data ]);
// Move first pointer forward and second pointer
// backward
first = first.next;
second = second.prev;
}
else if (first.data + second.data < target) {
first = first.next;
}
else {
second = second.prev;
}
}
return res;
}
// Function to create a doubly linked list node
function createNode(value) { return new Node(value); }
// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5
let head = createNode(1);
head.next = createNode(2);
head.next.prev = head;
head.next.next = createNode(4);
head.next.next.prev = head.next;
head.next.next.next = createNode(5);
head.next.next.next.prev = head.next.next;
let target = 7;
let pairs = findPairsWithGivenSum(head, target);
if (pairs.length === 0) {
console.log("No pairs found.");
}
else {
pairs.forEach(
pair => { console.log(`${pair[0]} ${pair[1]}`); });
}
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem