Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

How To Find Pairs With Given Sum In Linked List

Last Updated on November 11, 2022 by Prepbytes

This blog will explain how to find pairs with given sum in linked list. Firstly, bruteforce is discussed which helps to figure the quickest solution and the optimized solution is discussed which helps to figure the solution in an efficient way to find pairs with given sum in linked list.

How To Find Pairs With Given Sum In Linked List :

Given a sorted singly linked list and a value K, the task is to find pair whose sum is equal to K. We are not allowed to use any extra space and expected time complexity is O(n).
Print the number of pairs whose sum equals to K.

See original problem statement here

Example:
5 5
1 2 3 4 5

Output: 2
Since the pairs (2,3) and (1,4) add to give 5.

Approaches To Find Pairs With Given Sum In Linked List

Approach 1 (Brute force) To Find Pairs With Given Sum In Linked List:

Iterate over each node and check if any corresponding node with data sum-node->data is present.
This costs O(n*n) time.

 int count_pair(Node* head, int sum) 
     { 
      Node* p = head, *q; 
      while (p != NULL) { 
        q = p->next; 
        while (q != NULL) { 
           if ((p->data) + (q->data) == sum) { 
               count++;
           }      
           q = q->next;           
        } 
        p = p->next; 
    } 
    return count; 
    } 
 import java.util.*; 

      class prepbytes
      { 
      static class Node  
     { 
    int data,count=0; 
    Node next; 
    }; 
     static Node head; 
     static Node push(Node head_ref, int new_data) 
    { 
    Node new_node = new Node(); 
    new_node.data = new_data; 
    new_node.next = head_ref; 
    head_ref = new_node; 
    return head=head_ref; 
    } 
    static boolean check_pair_sum(Node head, int sum) 
    { 
    Node p = head, q; 
    while (p != null) 
    { 
        q = p.next; 
        while (q != null)  
        { 
            if ((p.data) + (q.data) == sum)  
            { 
                count++;
                return true; 
            }      
            q = q.next;          
        } 
        p = p.next; 
    } 
    return false; 
    }
    //main
     } 

Approach 2 (Hashing) To Find Pairs With Given Sum In Linked List:

Use hashtable(preferably map or set in C++) and initialize counter as 0.Insert the node data as you iterate over the list.If the corresponding node with data sum-node->data is found ,counter increases by one.

TIME COMPLEXITY To Find Pairs With Given Sum In Linked List:O(n)

 int count_pair(Node* head, int sum) 
    { 
     set<int> s; 

     Node* p = head; 
     while (p != NULL) { 
        int curr = p->data; 
        if (s.find(sum - curr) != s.end()) 
        count++;
        s.insert(p->data); 
        p = p->next; 
     } 
    return count; 
    }

Without using extra space!!!

Have you heard of MEMORY EFFICIENT DOUBLY LINKED LISTS?
XOR Linked list : In singly linked list, we can traverse list only in forward direction. We use XOR concept to convert a singly linked list to doubly linked list.

ALGORITHM To Find Pairs With Given Sum In Linked List:

        First we need to convert our singly linked list into doubly linked list. 

        Here we are given singly linked list structure node which have only next pointer not prev pointer,

        so to convert our singly linked list into doubly linked list we use memory efficient doubly linked list ( XOR linked list ).

        In XOR linked list each next pointer of singly linked list contains XOR of next and prev pointer.

        After converting singly linked list into doubly linked list 
        we initialize two pointers variables to find the candidate elements in the sorted doubly linked list. Initialize first with start of doubly linked list i.e;
        first = head and initialize second with last node of doubly linked list i.e; second = last_node.

        Here we don’t have random access, so to initialize pointer, we traverse the list till last node and assign last node to 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 either of two pointers become NULL, or they cross each other (first=next_node),
        or they become the same (first == second).
struct Node* XOR (struct Node *a, struct Node *b) 
{ 
    return (struct Node*) ((uintptr_t) (a) ^ (uintptr_t) (b)); 
} 

// Utility function to convert singly linked list 
// into XOR doubly linked list 
void convert(struct Node *head) 
{ 
    // first we store address of next node in it 
    // then take XOR of next node and previous node 
    // and store it in next pointer 
    struct Node *next_node; 

    // prev node stores the address of previously 
    // visited node 
    struct Node *prev = NULL; 

    // traverse list and store xor of address of 
    // next_node and prev node in next pointer of node 
    while (head != NULL) 
    { 
        // address of next node 
        next_node = head->next; 

        // xor of next_node and prev node 
        head->next = XOR(next_node, prev); 

        // update previous node 
        prev = head; 

        // move head forward 
        head = next_node; 
    } 
} 

// function to Find pair whose sum is equal to 
// given value x 
void pairSum(struct Node *head, int x) 
{ 
    // initialize first 
    struct Node *first = head; 

    // next_node and prev node to calculate xor again 
    // and find next and prev node while moving forward 
    // and backward direction from both the corners 
    struct Node *next_node = NULL, *prev = NULL; 

    // traverse list to initialize second pointer 
    // here we need to move in forward direction so to 
    // calculate next address we have to take xor 
    // with prev pointer because (a^b)^b = a 
    struct Node *second = head; 
    while (second->next != prev) 
    { 
        struct Node *temp = second; 
        second = XOR(second->next, prev); 
        prev = temp; 
    } 

    // now traverse from both the corners 
    next_node = NULL; 
    prev = NULL; 

    // here if we want to move forward then we must 
    // know the prev address to calculate next node 
    // and if we want to move backward then we must 
    // know the next_node address to calculate prev node 
    bool flag = false; 
    while (first != NULL && second != NULL && 
            first != second && first != next_node) 
    { 
        if ((first->data + second->data)==x) 
        { 
            count++; 
            //increment the counter
            flag = true; 

            // move first in forward 
            struct Node *temp = first; 
            first = XOR(first->next,prev); 
            prev = temp; 

            // move second in backward 
            temp = second; 
            second = XOR(second->next, next_node); 
            next_node = temp; 
        } 
        else
        { 
            if ((first->data + second->data) < x) 
            { 
                // move first in forward 
                struct Node *temp = first; 
                first = XOR(first->next,prev); 
                prev = temp; 
            } 
            else
            { 
                // move second in backward 
                struct Node *temp = second; 
                second = XOR(second->next, next_node); 
                next_node = temp; 
            } 
        } 
    } 
} 

This article has discussed two approaches to find pairs with given sum in linked list. Linked List and Hash Table are very essential topics in the perspective of technical interviews. Hope this blog helps you understand and solve the problem. To practice more problems on Linked lists,hash table you can check out MYCODE | Competitive Programming.

FAQs

1. What is head in the linked list?
The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null reference. A linked list is a dynamic data structure.

2. What is a hash table with an example?
Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access of data becomes very fast if we know the index of the desired data.

Leave a Reply

Your email address will not be published. Required fields are marked *