[Naive Approach] Check Every Pair - O(n ^ 2) Time and O(1) Space
The idea is to check every possible pair of nodes in the doubly linked list. For each node, traverse all the nodes after it and compare their sum with the target. If the sum equals the target, store the pair. After checking all pairs, return the result.
Working of Approach:
Start from the first node.
For every node, traverse all remaining nodes.
Compare the sum of every pair with the target.
Store every matching pair in the answer.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next,*prev;Node(intval){data=val;next=prev=nullptr;}};// Function to find all pairs with given sumvector<vector<int>>givenSumPairs(Node*head,inttarget){vector<vector<int>>res;// Check every possible pairfor(Node*first=head;first!=nullptr;first=first->next){for(Node*second=first->next;second!=nullptr;second=second->next){// Pair foundif(first->data+second->data==target)res.push_back({first->data,second->data});}}returnres;}// Insert node at endNode*insert(Node*head,intval){Node*newNode=newNode(val);if(!head)returnnewNode;Node*curr=head;while(curr->next)curr=curr->next;curr->next=newNode;newNode->prev=curr;returnhead;}intmain(){vector<int>arr={1,2,4,5,6,8,9};Node*head=nullptr;for(intx:arr)head=insert(head,x);inttarget=7;vector<vector<int>>ans=givenSumPairs(head,target);cout<<"[";for(inti=0;i<ans.size();i++){cout<<"["<<ans[i][0]<<", "<<ans[i][1]<<"]";if(i+1!=ans.size())cout<<", ";}cout<<"]";return0;}
Java
importjava.util.ArrayList;classNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}publicclassGFG{// Function to find all pairs with given sumpublicstaticArrayList<ArrayList<Integer>>givenSumPairs(Nodehead,inttarget){ArrayList<ArrayList<Integer>>res=newArrayList<>();// Check every possible pairfor(Nodefirst=head;first!=null;first=first.next){for(Nodesecond=first.next;second!=null;second=second.next){// Pair foundif(first.data+second.data==target){ArrayList<Integer>pair=newArrayList<>();pair.add(first.data);pair.add(second.data);res.add(pair);}}}returnres;}// Insert node at endpublicstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}publicstaticvoidmain(String[]args){int[]arr={1,2,4,5,6,8,9};Nodehead=null;for(intx:arr)head=insert(head,x);inttarget=7;ArrayList<ArrayList<Integer>>ans=givenSumPairs(head,target);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print("["+ans.get(i).get(0)+", "+ans.get(i).get(1)+"]");if(i+1!=ans.size())System.out.print(", ");}System.out.print("]");}}
Python
classNode:def__init__(self,val):self.data=valself.next=self.prev=None# Function to find all pairs with given sumdefgivenSumPairs(head,target):res=[]# Check every possible pairfirst=headwhilefirstisnotNone:second=first.nextwhilesecondisnotNone:# Pair foundiffirst.data+second.data==target:res.append([first.data,second.data])second=second.nextfirst=first.nextreturnres# Insert node at enddefinsert(head,val):newNode=Node(val)ifheadisNone:returnnewNodecurr=headwhilecurr.nextisnotNone:curr=curr.nextcurr.next=newNodenewNode.prev=currreturnheadif__name__=='__main__':arr=[1,2,4,5,6,8,9]head=Noneforxinarr:head=insert(head,x)target=7ans=givenSumPairs(head,target)print('[',end='')foriinrange(len(ans)):print('['+str(ans[i][0])+','+str(ans[i][1])+']')ifi+1!=len(ans):print(', ',end='')print(']')
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}classGFG{// Function to find all pairs with given sumstaticList<List<int>>givenSumPairs(Nodehead,inttarget){List<List<int>>res=newList<List<int>>();// Check every possible pairfor(Nodefirst=head;first!=null;first=first.next){for(Nodesecond=first.next;second!=null;second=second.next){// Pair foundif(first.data+second.data==target){res.Add(newList<int>{first.data,second.data});}}}returnres;}// Insert node at endstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}staticvoidMain(string[]args){int[]arr={1,2,4,5,6,8,9};Nodehead=null;foreach(intxinarr)head=insert(head,x);inttarget=7;List<List<int>>ans=givenSumPairs(head,target);Console.Write('[');for(inti=0;i<ans.Count;i++){Console.Write('['+ans[i][0]+", "+ans[i][1]+']');if(i+1!=ans.Count)Console.Write(", ");}Console.Write(']');}}
JavaScript
classNode{constructor(val){this.data=val;this.next=this.prev=null;}}// Function to find all pairs with given sumfunctiongivenSumPairs(head,target){letres=[];// Check every possible pairletfirst=head;while(first!==null){letsecond=first.next;while(second!==null){// Pair foundif(first.data+second.data===target){res.push([first.data,second.data]);}second=second.next;}first=first.next;}returnres;}// Insert node at endfunctioninsert(head,val){letnewNode=newNode(val);if(!head)returnnewNode;letcurr=head;while(curr.next!==null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}// Driver Codeletarr=[1,2,4,5,6,8,9];lethead=null;for(letxofarr)head=insert(head,x);lettarget=7;letans=givenSumPairs(head,target);console.log("[");for(leti=0;i<ans.length;i++){console.log("["+ans[i][0]+", "+ans[i][1]+"]");if(i+1!==ans.length)console.log(", ");}console.log("]");
Output
[[1, 6], [2, 5]]
[Better Approach] Using Hashing - O(n log n) Time and O(n) Space
The idea is to traverse the doubly linked list once while storing the visited node values in a hash set. For each node, check whether its required complement (target - current value) is already present in the hash set. If it is, store the pair; otherwise, insert the current value into the hash set and continue.
Working of Approach:
Traverse the linked list from left to right.
Maintain a hash set of visited node values.
Check whether the required complement already exists.
Store every matching pair in the result.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next,*prev;Node(intval){data=val;next=prev=nullptr;}};// Function to find all pairs with given sumvector<vector<int>>givenSumPairs(Node*head,inttarget){unordered_set<int>st;vector<vector<int>>res;// Traverse the linked listwhile(head){intneed=target-head->data;// Pair foundif(st.count(need))res.push_back({need,head->data});// Insert current value into hash setst.insert(head->data);head=head->next;}// Sort pairs according to first elementsort(res.begin(),res.end());returnres;}// Insert node at endNode*insert(Node*head,intval){Node*newNode=newNode(val);if(!head)returnnewNode;Node*curr=head;while(curr->next)curr=curr->next;curr->next=newNode;newNode->prev=curr;returnhead;}intmain(){vector<int>arr={1,2,4,5,6,8,9};Node*head=nullptr;for(intx:arr)head=insert(head,x);inttarget=7;vector<vector<int>>ans=givenSumPairs(head,target);cout<<"[";for(inti=0;i<ans.size();i++){cout<<"["<<ans[i][0]<<", "<<ans[i][1]<<"]";if(i+1!=ans.size())cout<<", ";}cout<<"]";return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;importjava.util.HashSet;classNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}publicclassGFG{// Function to find all pairs with given sumpublicstaticArrayList<ArrayList<Integer>>givenSumPairs(Nodehead,inttarget){HashSet<Integer>st=newHashSet<>();ArrayList<ArrayList<Integer>>res=newArrayList<>();// Traverse the linked listwhile(head!=null){intneed=target-head.data;// Pair foundif(st.contains(need)){ArrayList<Integer>pair=newArrayList<>();pair.add(need);pair.add(head.data);res.add(pair);}// Insert current value into hash setst.add(head.data);head=head.next;}// Sort pairs according to first elementCollections.sort(res,(a,b)->Integer.compare(a.get(0),b.get(0)));returnres;}// Insert node at endpublicstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}publicstaticvoidmain(String[]args){int[]arr={1,2,4,5,6,8,9};Nodehead=null;for(intx:arr)head=insert(head,x);inttarget=7;ArrayList<ArrayList<Integer>>ans=givenSumPairs(head,target);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print("["+ans.get(i).get(0)+", "+ans.get(i).get(1)+"]");if(i+1!=ans.size())System.out.print(", ");}System.out.print("]");}}
Python
fromtypingimportList,TupleclassNode:def__init__(self,val):self.data=valself.next=Noneself.prev=None# Function to find all pairs with given sumdefgivenSumPairs(head,target)->List[Tuple[int,int]]:st=set()res=[]# Traverse the linked listwhilehead:need=target-head.data# Pair foundifneedinst:res.append((need,head.data))# Insert current value into hash setst.add(head.data)head=head.next# Sort pairs according to first elementres.sort(key=lambdax:x[0])returnres# Insert node at enddefinsert(head,val):newNode=Node(val)ifnothead:returnnewNodecurr=headwhilecurr.next:curr=curr.nextcurr.next=newNodenewNode.prev=currreturnheadif__name__=='__main__':arr=[1,2,4,5,6,8,9]head=Noneforxinarr:head=insert(head,x)target=7ans=givenSumPairs(head,target)print('[',end='')foriinrange(len(ans)):print(f'[{ans[i][0]}, {ans[i][1]}]',end='')ifi+1!=len(ans):print(', ',end='')print(']')
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}publicclassGFG{// Function to find all pairs with given sumpublicList<List<int>>givenSumPairs(Nodehead,inttarget){List<List<int>>res=newList<List<int>>();if(head==null)returnres;Nodeleft=head;Noderight=head;// Move right to the last nodewhile(right.next!=null)right=right.next;// Find pairswhile(left!=right&&right.next!=left){intsum=left.data+right.data;if(sum==target){List<int>pair=newList<int>();pair.Add(left.data);pair.Add(right.data);res.Add(pair);left=left.next;right=right.prev;}elseif(sum<target){left=left.next;}else{right=right.prev;}}returnres;}// Insert node at endpublicstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}publicstaticvoidMain(){int[]arr={1,2,4,5,6,8,9};Nodehead=null;foreach(intxinarr)head=insert(head,x);inttarget=7;GFGob=newGFG();List<List<int>>ans=ob.givenSumPairs(head,target);Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write("["+ans[i][0]+", "+ans[i][1]+"]");if(i+1!=ans.Count)Console.Write(", ");}Console.Write("]");}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;this.prev=null;}}// Function to find all pairs with given sumfunctiongivenSumPairs(head,target){letst=newSet();letres=[];// Traverse the linked listwhile(head){letneed=target-head.data;// Pair foundif(st.has(need))res.push([need,head.data]);// Insert current value into hash setst.add(head.data);head=head.next;}// Sort pairs according to first elementres.sort((a,b)=>a[0]-b[0]);returnres;}// Insert node at endfunctioninsert(head,val){letnewNode=newNode(val);if(!head)returnnewNode;letcurr=head;while(curr.next)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}// Driver Codeletarr=[1,2,4,5,6,8,9];lethead=null;for(letxofarr)head=insert(head,x);lettarget=7;letans=givenSumPairs(head,target);console.log("[");for(leti=0;i<ans.length;i++){console.log(`[${ans[i][0]}, ${ans[i][1]}]`);if(i+1!=ans.length)console.log(", ");}console.log("]");
Output
[[1, 6], [2, 5]]
[Expected Approach] Using Two Pointer Technique - O(n) Time and O(1) Space
The idea is to use two pointers because the doubly linked list is sorted. Place one pointer at the beginning and the other at the end of the list. Compare their sum with the target and move the appropriate pointer accordingly. Whenever the sum equals the target, store the pair and continue until the pointers meet or cross.
Working of Approach:
Place one pointer at the first node and the other at the last node.
If the sum equals the target, store the pair and move both pointers inward.
If the sum is smaller, move the left pointer forward.
Otherwise, move the right pointer backward.
Let us understand with an example: Input: target = 7
Initialize two pointers: ptr1 at the first node (1) and ptr2 at the last node (9). Since 1 + 9 = 10 is greater than 7, move ptr2 to 8, then to 6.
Now 1 + 6 = 7, which matches the target. Store the pair (1, 6) and move both pointers inward to 2 and 5.
Again, 2 + 5 = 7, so store the pair (2, 5) and move the pointers inward to 4 and 4.
Both pointers now point to the same node, so the traversal stops as all possible pairs have been checked.
The final result is [[1, 6], [2, 5]].
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of Doubly Linked List NodeclassNode{public:intdata;Node*next,*prev;Node(intval){data=val;next=prev=nullptr;}};vector<vector<int>>givenSumPairs(Node*head,inttarget){Node*ptr1=head,*ptr2=head;// Move ptr2 to the end of the linked listwhile(ptr2->next){ptr2=ptr2->next;}vector<vector<int>>res;// Find pairs with the given sumwhile(ptr1!=ptr2&&ptr2->next!=ptr1){intsum=ptr1->data+ptr2->data;if(sum==target){res.push_back({ptr1->data,ptr2->data});ptr1=ptr1->next;ptr2=ptr2->prev;}elseif(sum<target){ptr1=ptr1->next;}else{ptr2=ptr2->prev;}}returnres;}// Insert node at endNode*insert(Node*head,intval){Node*newNode=newNode(val);if(!head)returnnewNode;Node*curr=head;while(curr->next)curr=curr->next;curr->next=newNode;newNode->prev=curr;returnhead;}intmain(){vector<int>arr={1,2,4,5,6,8,9};Node*head=nullptr;for(intx:arr)head=insert(head,x);inttarget=7;vector<vector<int>>ans=givenSumPairs(head,target);cout<<"[";for(inti=0;i<ans.size();i++){cout<<"["<<ans[i][0]<<", "<<ans[i][1]<<"]";if(i+1!=ans.size())cout<<", ";}cout<<"]";return0;}
Java
importjava.util.ArrayList;classNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}publicclassGFG{// Function to find all pairs with given sumpublicstaticArrayList<ArrayList<Integer>>givenSumPairs(Nodehead,inttarget){Nodeptr1=head,ptr2=head;// Move ptr2 to the end of the linked listwhile(ptr2.next!=null){ptr2=ptr2.next;}ArrayList<ArrayList<Integer>>res=newArrayList<>();// Find pairs with the given sumwhile(ptr1!=ptr2&&ptr2.next!=ptr1){intsum=ptr1.data+ptr2.data;if(sum==target){ArrayList<Integer>pair=newArrayList<>();pair.add(ptr1.data);pair.add(ptr2.data);res.add(pair);ptr1=ptr1.next;ptr2=ptr2.prev;}elseif(sum<target){ptr1=ptr1.next;}else{ptr2=ptr2.prev;}}returnres;}// Insert node at endpublicstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}publicstaticvoidmain(String[]args){int[]arr={1,2,4,5,6,8,9};Nodehead=null;for(intx:arr)head=insert(head,x);inttarget=7;ArrayList<ArrayList<Integer>>ans=givenSumPairs(head,target);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print("["+ans.get(i).get(0)+", "+ans.get(i).get(1)+"]");if(i+1!=ans.size())System.out.print(", ");}System.out.print("]");}}
Python
classNode:def__init__(self,val):self.data=valself.next=Noneself.prev=NonedefgivenSumPairs(head,target):ptr1=headptr2=head# Move ptr2 to the end of the linked listwhileptr2.next:ptr2=ptr2.nextres=[]# Find pairs with the given sumwhileptr1!=ptr2andptr2.next!=ptr1:sum=ptr1.data+ptr2.dataifsum==target:res.append([ptr1.data,ptr2.data])ptr1=ptr1.nextptr2=ptr2.prevelifsum<target:ptr1=ptr1.nextelse:ptr2=ptr2.prevreturnresdefinsert(head,val):newNode=Node(val)ifnothead:returnnewNodecurr=headwhilecurr.next:curr=curr.nextcurr.next=newNodenewNode.prev=currreturnheadif__name__=='__main__':arr=[1,2,4,5,6,8,9]head=Noneforxinarr:head=insert(head,x)target=7ans=givenSumPairs(head,target)print('[',end='')foriinrange(len(ans)):print('[{}, {}]'.format(ans[i][0],ans[i][1]),end='')ifi+1!=len(ans):print(', ',end='')print(']')
C#
usingSystem;usingSystem.Collections.Generic;// Structure of Doubly Linked List NodepublicclassNode{publicintdata;publicNodenext,prev;publicNode(intval){data=val;next=prev=null;}}publicclassGFG{publicstaticList<List<int>>givenSumPairs(Nodehead,inttarget){Nodeptr1=head,ptr2=head;// Move ptr2 to the end of the linked listwhile(ptr2.next!=null){ptr2=ptr2.next;}List<List<int>>res=newList<List<int>>();// Find pairs with the given sumwhile(ptr1!=ptr2&&ptr2.next!=ptr1){intsum=ptr1.data+ptr2.data;if(sum==target){res.Add(newList<int>{ptr1.data,ptr2.data});ptr1=ptr1.next;ptr2=ptr2.prev;}elseif(sum<target){ptr1=ptr1.next;}else{ptr2=ptr2.prev;}}returnres;}// Insert node at endpublicstaticNodeinsert(Nodehead,intval){NodenewNode=newNode(val);if(head==null)returnnewNode;Nodecurr=head;while(curr.next!=null)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}publicstaticvoidMain(){int[]arr={1,2,4,5,6,8,9};Nodehead=null;foreach(intxinarr)head=insert(head,x);inttarget=7;List<List<int>>ans=givenSumPairs(head,target);Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write("["+ans[i][0]+", "+ans[i][1]+"]");if(i+1!=ans.Count)Console.Write(", ");}Console.Write("]");}}
JavaScript
// Structure of Doubly Linked List NodeclassNode{constructor(val){this.data=val;this.next=this.prev=null;}}functiongivenSumPairs(head,target){letptr1=head,ptr2=head;// Move ptr2 to the end of the linked listwhile(ptr2.next){ptr2=ptr2.next;}letres=[];// Find pairs with the given sumwhile(ptr1!==ptr2&&ptr2.next!==ptr1){letsum=ptr1.data+ptr2.data;if(sum===target){res.push([ptr1.data,ptr2.data]);ptr1=ptr1.next;ptr2=ptr2.prev;}elseif(sum<target){ptr1=ptr1.next;}else{ptr2=ptr2.prev;}}returnres;}// Insert node at endfunctioninsert(head,val){letnewNode=newNode(val);if(!head)returnnewNode;letcurr=head;while(curr.next)curr=curr.next;curr.next=newNode;newNode.prev=curr;returnhead;}// Driver Codeletarr=[1,2,4,5,6,8,9];lethead=null;for(letxofarr)head=insert(head,x);lettarget=7;letans=givenSumPairs(head,target);console.log("[");for(leti=0;i<ans.length;i++){console.log("["+ans[i][0]+","+ans[i][1]+"]");if(i+1!==ans.length)console.log(", ");}console.log("]");