Find pairs with given sum in doubly linked list
Last Updated :
04 Dec, 2024
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
Find quadruplets with given sum in a Doubly Linked List Given a sorted doubly linked list and an integer X, the task is to print all the quadruplets in the doubly linked list whose sum is X. Examples: Input: LL: -3 ? 1 ? 2 ? 3 ? 5 ? 6, X = 7Output:-3 2 3 5 -3 3 1 6Explanation: The quadruplets having sum 7( = X) are: {-3, 2, 3, 5}, {-3, 3, 1, 6}. Input: L
14 min read
Find pairs with given product in a sorted Doubly Linked List Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in the doubly linked list whose product is equal to given value x, without using any extra space. Examples: Input : List = 1 <=> 2 <=> 4 <=> 5 <=> 6 <=> 8 <=> 9 x = 8 Output
10 min read
Maximum sum contiguous nodes in the given linked list Given a linked list, the task is to find the maximum sum for any contiguous nodes. Examples: Input: -2 -> -3 -> 4 -> -1 -> -2 -> 1 -> 5 -> -3 -> NULL Output: 7 4 -> -1 -> -2 -> 1 -> 5 is the sub-list with the given sum. Input: 1 -> 2 -> 3 -> 4 -> NULL
11 min read
Print all triplets with sum S in given sorted Linked List Given a sorted singly linked list as list of N distinct nodes (no two nodes have the same data) and an integer S. The task is to find all distinct triplets in the list that sum up to given integer S. Examples: Input: list = 1->2->4->5->6->8->9, S = 15Output: [(1, 5, 9), (1, 6, 8),
15+ min read
Program to find size of Doubly Linked List Given a doubly linked list, The task is to find the size of the given doubly linked list. Example:Input : 1<->2<->3<->4output : 4Explanation: The size is 4 as there are 4 nodes in the doubly linked list. Input : 1<->2output : 2Approach - Using While Loop â O(n) Time and O(1)
7 min read