Find pairs with given sum in doubly linked list
Last Updated :
06 Oct, 2023
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 given value x, without using any extra space?
Example:
Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9
x = 7
Output: (6, 1), (5,2)
The expected time complexity is O(n) and auxiliary space is O(1).
A simple approach for this problem is to one by one pick each node and find a second element whose sum is equal to x in the remaining list by traversing in the forward direction. The time complexity for this problem will be O(n^2), n is the total number of nodes in the doubly linked list.
An efficient solution for this problem is the same as this article. Here is the algorithm :
- 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 i.e; first=head and initialize second with the last node of the doubly linked list i.e; second=last_node.
- We initialize first and second pointers as first and last nodes. Here we don’t have random access, so to find the second pointer, we traverse the list to initialize the second.
- 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.
- Loop termination conditions are also different from arrays. The loop terminates when two pointers cross each other (second->next = first), or they become the same (first == second).
- The case when no pairs are present will be handled by the condition “first==second”
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next, *prev;
};
void pairSum( struct Node *head, int x)
{
struct Node *first = head;
struct Node *second = head;
while (second->next != NULL)
second = second->next;
bool found = false ;
while (first != second && second->next != first)
{
if ((first->data + second->data) == x)
{
found = true ;
cout << "(" << first->data<< ", "
<< second->data << ")" << endl;
first = first->next;
second = second->prev;
}
else
{
if ((first->data + second->data) < x)
first = first->next;
else
second = second->prev;
}
}
if (found == false )
cout << "No pair found" ;
}
void insert( struct Node **head, int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
int main()
{
struct Node *head = NULL;
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 7;
pairSum(head, x);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static class Node {
int data;
Node next, prev;
};
static void pairSum(Node head, int x)
{
Node first = head;
Node second = head;
while (second.next != null )
second = second.next;
boolean found = false ;
while (first != second && second.next != first) {
if ((first.data + second.data) == x) {
found = true ;
System.out.println( "(" + first.data + ", "
+ second.data + ")" );
first = first.next;
second = second.prev;
}
else {
if ((first.data + second.data) < x)
first = first.next;
else
second = second.prev;
}
}
if (found == false )
System.out.println( "No pair found" );
}
static Node insert(Node head, int data)
{
Node temp = new Node();
temp.data = data;
temp.next = temp.prev = null ;
if (head == null )
(head) = temp;
else {
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return temp;
}
public static void main(String args[])
{
Node head = null ;
head = insert(head, 9 );
head = insert(head, 8 );
head = insert(head, 6 );
head = insert(head, 5 );
head = insert(head, 4 );
head = insert(head, 2 );
head = insert(head, 1 );
int x = 7 ;
pairSum(head, x);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
self .prev = None
def pairSum(head, x):
first = head
second = head
while (second. next ! = None ):
second = second. next
found = False
while (first ! = second and second. next ! = first):
if ((first.data + second.data) = = x):
found = True
print ( "(" , first.data, "," ,
second.data, ")" )
first = first. next
second = second.prev
else :
if ((first.data + second.data) < x):
first = first. next
else :
second = second.prev
if (found = = False ):
print ( "No pair found" )
def insert(head, data):
temp = Node(data)
if not head:
head = temp
else :
temp. next = head
head.prev = temp
head = temp
return head
if __name__ = = '__main__' :
head = None
head = insert(head, 9 )
head = insert(head, 8 )
head = insert(head, 6 )
head = insert(head, 5 )
head = insert(head, 4 )
head = insert(head, 2 )
head = insert(head, 1 )
x = 7
pairSum(head, x)
|
C#
using System;
class GFG
{
class Node
{
public int data;
public Node next, prev;
};
static void pairSum( Node head, int x)
{
Node first = head;
Node second = head;
while (second.next != null )
second = second.next;
bool found = false ;
while (first != second && second.next != first)
{
if ((first.data + second.data) == x)
{
found = true ;
Console.WriteLine( "(" + first.data +
", " + second.data + ")" );
first = first.next;
second = second.prev;
}
else
{
if ((first.data + second.data) < x)
first = first.next;
else
second = second.prev;
}
}
if (found == false )
Console.WriteLine( "No pair found" );
}
static Node insert(Node head, int data)
{
Node temp = new Node();
temp.data = data;
temp.next = temp.prev = null ;
if (head == null )
(head) = temp;
else
{
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return temp;
}
public static void Main(String []args)
{
Node head = null ;
head = insert(head, 9);
head = insert(head, 8);
head = insert(head, 6);
head = insert(head, 5);
head = insert(head, 4);
head = insert(head, 2);
head = insert(head, 1);
int x = 7;
pairSum(head, x);
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .next = this .prev = null ;
}
}
function pairSum(head, x)
{
let first = head;
let second = head;
while (second.next != null )
second = second.next;
let found = false ;
while ( first != second && second.next != first)
{
if ((first.data + second.data) == x)
{
found = true ;
document.write( "(" + first.data +
", " + second.data + ")<br>" );
first = first.next;
second = second.prev;
}
else
{
if ((first.data + second.data) < x)
first = first.next;
else
second = second.prev;
}
}
if (found == false )
document.write( "No pair found<br>" );
}
function insert(head,data)
{
let temp = new Node();
temp.data = data;
temp.next = temp.prev = null ;
if (head == null )
(head) = temp;
else
{
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return temp;
}
let head = null ;
head = insert(head, 9);
head = insert(head, 8);
head = insert(head, 6);
head = insert(head, 5);
head = insert(head, 4);
head = insert(head, 2);
head = insert(head, 1);
let x = 7;
pairSum(head, x);
</script>
|
Time complexity : O(n)
Auxiliary space : O(1)
If linked list is not sorted, then we can sort the list as a first step. But in that case overall time complexity would become O(n Log n). We can use Hashing in such cases if extra space is not a constraint. The hashing based solution is same as method 2 here.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...