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>usingnamespacestd;classNode{public:intdata;Node*next;Node(intvalue){data=value;next=nullptr;}};// Function to find pairs in the doubly linked list// whose sum equals the given value xvector<pair<int,int>>findPairsWithGivenSum(Node*head,inttarget){vector<pair<int,int>>ans;unordered_map<int,Node*>visited;Node*currNode=head;// Traverse the doubly linked listwhile(currNode!=nullptr){intx=target-currNode->data;// Check if the target exists in the mapif(visited.find(x)!=visited.end()){// Pair foundans.push_back({x,currNode->data});}// Store the current node's value in the mapvisited[currNode->data]=currNode;currNode=currNode->next;}sort(ans.begin(),ans.end());returnans;}intmain(){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(4);head->next->next->next=newNode(5);inttarget=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;}}return0;}
Java
// Java program to find a pair with given sum x// using mapimportjava.util.*;classNode{intdata;Nodenext;Node(intvalue){data=value;next=null;}}classGfG{staticArrayList<ArrayList<Integer>>findPairsWithGivenSum(inttarget,Nodehead){ArrayList<ArrayList<Integer>>ans=newArrayList<>();HashSet<Integer>visited=newHashSet<>();NodecurrNode=head;// Traverse the doubly linked listwhile(currNode!=null){intx=target-currNode.data;// Check if the target exists in the visited setif(visited.contains(x)){// Pair found, add it to the answerArrayList<Integer>pair=newArrayList<>();pair.add(x);pair.add(currNode.data);ans.add(pair);}// Add the current node's value to the visited// setvisited.add(currNode.data);currNode=currNode.next;}// Sort the pairs by the first element of the pairCollections.sort(ans,(a,b)->a.get(0).compareTo(b.get(0)));returnans;}publicstaticvoidmain(String[]args){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);inttarget=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 mapclassNode:def__init__(self,value):self.data=valueself.next=NonedeffindPairsWithGivenSum(target,head):ans=[]visited=set()currNode=head# Traverse the doubly linked listwhilecurrNodeisnotNone:x=target-currNode.data# Check if the target exists in the visited setifxinvisited:# Pair found, add it to the answerans.append([x,currNode.data])# Add the current node's value to the visited setvisited.add(currNode.data)currNode=currNode.next# Sort the pairs by the first element of the pairans.sort(key=lambdapair:pair[0])returnans# Helper function to create a linked listdefcreate_linked_list(values):head=Node(values[0])current=headforvalueinvalues[1:]:current.next=Node(value)current=current.nextreturnheadif__name__=="__main__":# Create a doubly linked list: 1 -> 2 -> 4 -> 5values=[1,2,4,5]head=create_linked_list(values)target=7pairs=findPairsWithGivenSum(target,head)ifnotpairs:print("No pairs found.")else:forpairinpairs:print(pair[0],pair[1])
C#
// C# program to find a pair with given sum x// using mapusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intvalue){data=value;next=null;}}classGfG{staticList<Tuple<int,int>>FindPairsWithGivenSum(Nodehead,inttarget){List<Tuple<int,int>>ans=newList<Tuple<int,int>>();HashSet<int>visited=newHashSet<int>();NodecurrNode=head;// Traverse the doubly linked listwhile(currNode!=null){intx=target-currNode.data;// Check if the target exists in the visited setif(visited.Contains(x)){// Pair foundans.Add(newTuple<int,int>(x,currNode.data));}// Add the current node's value to the visited setvisited.Add(currNode.data);currNode=currNode.next;}// Sort the pairsans.Sort((a,b)=>a.Item1.CompareTo(b.Item1));returnans;}staticvoidMain(){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);inttarget=7;List<Tuple<int,int>>pairs=FindPairsWithGivenSum(head,target);if(pairs.Count==0){Console.WriteLine("No pairs found.");}else{foreach(varpairinpairs){Console.WriteLine(pair.Item1+" "+pair.Item2);}}}}
JavaScript
// JavaScript program to find a pair with given sum x// using mapclassNode{constructor(value){this.data=value;this.next=null;}}functionfindPairsWithGivenSum(head,target){letans=[];letvisited=newSet();letcurrNode=head;// Traverse the doubly linked listwhile(currNode!==null){letx=target-currNode.data;// Check if the target exists in the visited setif(visited.has(x)){// Pair foundans.push([x,currNode.data]);}// Add the current node's value to the visited setvisited.add(currNode.data);currNode=currNode.next;}// Sort the pairsans.sort((a,b)=>a[0]-b[0]);returnans;}lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);lettarget=7;letpairs=findPairsWithGivenSum(head,target);if(pairs.length===0){console.log("No pairs found.");}else{for(letpairofpairs){console.log(pair[0]+" "+pair[1]);}}
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.
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>usingnamespacestd;classNode{public:intdata;Node*next,*prev;Node(intvalue){data=value;next=nullptr;prev=nullptr;}};// Function to find pairs in the doubly// linked list whose sum equals the given value xvector<pair<int,int>>findPairsWithGivenSum(Node*head,inttarget){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 DLLwhile(second->next!=nullptr)second=second->next;// To track if we find a pair or notboolfound=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 pairif((first->data+second->data)==target){found=true;res.push_back({first->data,second->data});// Move first in forward directionfirst=first->next;// Move second in backward directionsecond=second->prev;}else{if((first->data+second->data)<target)first=first->next;elsesecond=second->prev;}}// If no pair is foundreturnres;}intmain(){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Node*head=newNode(1);head->next=newNode(2);head->next->prev=head;head->next->next=newNode(4);head->next->next->prev=head->next;head->next->next->next=newNode(5);head->next->next->next->prev=head->next->next;inttarget=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;}}return0;}
Java
// Java program to find a pair with given sum target.importjava.util.ArrayList;classNode{intdata;Nodenext,prev;Node(intvalue){data=value;next=prev=null;}}classGfG{// Function to find pairs in the doubly linked list// whose sum equals the given value targetstaticArrayList<ArrayList<Integer>>findPairsWithGivenSum(inttarget,Nodehead){ArrayList<ArrayList<Integer>>res=newArrayList<>();// Set two pointers, first to the beginning of DLL// and second to the end of DLL.Nodefirst=head;Nodesecond=head;// Move second to the end of the DLLwhile(second.next!=null)second=second.next;// Iterate through the list using two pointers to// find pairswhile(first!=second&&second.next!=first){// If the sum of the two nodes is equal to// target, add the pairif((first.data+second.data)==target){ArrayList<Integer>pair=newArrayList<>();pair.add(first.data);pair.add(second.data);res.add(pair);// Move first in forward directionfirst=first.next;// Move second in backward directionsecond=second.prev;}else{if((first.data+second.data)<target)first=first.next;elsesecond=second.prev;}}returnres;}publicstaticvoidmain(String[]args){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Nodehead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(4);head.next.next.prev=head.next;head.next.next.next=newNode(5);head.next.next.next.prev=head.next.next;inttarget=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.classNode:def__init__(self,value):self.data=valueself.next=Noneself.prev=None# Function to find pairs in the doubly linked list# whose sum equals the given value targetdeffind_pairs_with_given_sum(head,target):res=[]# Set two pointers, first to the beginning of DLL# and second to the end of DLL.first=headsecond=head# Move second to the end of the DLLwhilesecond.nextisnotNone:second=second.next# The loop terminates when two pointers# cross each other (second.next == first),# or they become the same (first == second)whilefirst!=secondandsecond.next!=first:if(first.data+second.data)==target:# Add pair to the result listres.append((first.data,second.data))# Move first in forward directionfirst=first.next# Move second in backward directionsecond=second.prevelif(first.data+second.data)<target:first=first.nextelse:second=second.prevreturnresif__name__=="__main__":# Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5head=Node(1)head.next=Node(2)head.next.prev=headhead.next.next=Node(4)head.next.next.prev=head.nexthead.next.next.next=Node(5)head.next.next.next.prev=head.next.nexttarget=7pairs=find_pairs_with_given_sum(head,target)ifnotpairs:print("No pairs found.")else:forpairinpairs:print(pair[0],pair[1])
C#
// C# program to find a pair with given sum target.usingSystem;usingSystem.Collections.Generic;classNode{publicintData;publicNodeNext,Prev;publicNode(intvalue){Data=value;Next=null;Prev=null;}}classGfG{// Function to find pairs in the doubly linked list// whose sum equals the given value targetstaticList<Tuple<int,int>>FindPairsWithGivenSum(Nodehead,inttarget){List<Tuple<int,int>>result=newList<Tuple<int,int>>();Nodefirst=head;Nodesecond=head;// Move second pointer to the last nodewhile(second.Next!=null)second=second.Next;// Iterate using two pointers to find pairswhile(first!=second&&second.Next!=first){if(first.Data+second.Data==target){result.Add(Tuple.Create(first.Data,second.Data));// Move first in forward directionfirst=first.Next;// Move second in backward directionsecond=second.Prev;}elseif(first.Data+second.Data<target){first=first.Next;}else{second=second.Prev;}}returnresult;}staticvoidMain(string[]args){// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5Nodehead=newNode(1);head.Next=newNode(2);head.Next.Prev=head;head.Next.Next=newNode(4);head.Next.Next.Prev=head.Next;head.Next.Next.Next=newNode(5);head.Next.Next.Next.Prev=head.Next.Next;inttarget=7;List<Tuple<int,int>>pairs=FindPairsWithGivenSum(head,target);if(pairs.Count==0){Console.WriteLine("No pairs found.");}else{foreach(varpairinpairs){Console.WriteLine($"{pair.Item1} {pair.Item2}");}}}}
JavaScript
// JavaScript program to find a pair with given sum target.classNode{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 targetfunctionfindPairsWithGivenSum(head,target){letres=[];letfirst=head;letsecond=head;// Move second pointer to the end of the DLLwhile(second.next!==null){second=second.next;}// Iterate through the list using two pointerswhile(first!==second&&second.next!==first){if(first.data+second.data===target){res.push([first.data,second.data]);// Move first pointer forward and second pointer// backwardfirst=first.next;second=second.prev;}elseif(first.data+second.data<target){first=first.next;}else{second=second.prev;}}returnres;}// Function to create a doubly linked list nodefunctioncreateNode(value){returnnewNode(value);}// Create a doubly linked list: 1 <-> 2 <-> 4 <-> 5lethead=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;lettarget=7;letpairs=findPairsWithGivenSum(head,target);if(pairs.length===0){console.log("No pairs found.");}else{pairs.forEach(pair=>{console.log(`${pair[0]}${pair[1]}`);});}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.