Open In App

Find pair for given sum in a sorted singly linked without extra space

Improve
Improve
Like Article
Like
Save
Share
Report

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

Examples: 

Input : head = 3-->6-->7-->8-->9-->10-->11 , x=17
Output: (6, 11), (7, 10), (8, 9)

Hint : We are allowed to modify original linked list

A simple solution for this problem is to take each element one by one and traverse the remaining list in forward direction to find second element whose sum is equal to given value x. Time complexity for this approach will be O(n2).

An efficient solution for this problem is based on ideas discussed in below articles. 
Find pair in doubly linked list : We use the same algorithm that traverses linked list from both ends. 
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.

Below are steps : 

  • 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 same (first == second).

Implementation:

C++




// C++ program to find pair with given sum in a singly
// linked list in O(n) time and no extra space.
#include<bits/stdc++.h>
using namespace std;
 
/* Link list node */
struct Node
{
    int data;
 
    /* also contains XOR of next and
    previous node after conversion*/
    struct Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
    of a list and an int, push a new node on the front
    of the list. */
void insert(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* returns XORed value of the node addresses */
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)
        {
            cout << "(" << first->data << ","
                 << second->data << ")" << endl;
 
            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;
            }
        }
    }
    if (flag == false)
        cout << "No pair found" << endl;
}
 
// Driver program to run the case
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    int x = 17;
 
    /* Use insert() to construct below list
    3-->6-->7-->8-->9-->10-->11 */
    insert(&head, 11);
    insert(&head, 10);
    insert(&head, 9);
    insert(&head, 8);
    insert(&head, 7);
    insert(&head, 6);
    insert(&head, 3);
 
    // convert singly linked list into XOR doubly
    // linked list
    convert(head);
    pairSum(head,x);
    return 0;
}


Java




import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.Collections;
 
// Class representing a Node in the XOR Doubly Linked List
class Node {
    int data;
    Node next;
 
    // Constructor to create a new Node with data
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
 
    // Function to compute the XOR of two Nodes
    public Node xor(Node a, Node b) {
        return a != null ? (b != null ? (Objects.hash(a, b) == 0 ? null : this) : a) : b;
    }
}
 
public class XORLinkedList {
    // Head of the XOR Doubly Linked List
    private Node head;
 
    // Constructor to initialize an empty list
    public XORLinkedList() {
        this.head = null;
    }
 
    // Function to insert a new Node with data at the beginning of the list
    public void insert(int newData) {
        Node newNode = new Node(newData);
        if (head != null) {
            newNode.next = head;
            head = newNode;
        } else {
            head = newNode;
        }
    }
 
    // Function to find pairs in the list whose sum is equal to a given value
    public List<Pair> findPairsWithSum(int x) {
        if (head == null) {
            System.out.println("No elements in the list.");
            return Collections.emptyList();
        }
 
        Set<Integer> visitedValues = new HashSet<>();
        Node current = head;
        List<Pair> pairs = new ArrayList<>();
 
        while (current != null) {
            int neededValue = x - current.data;
            if (visitedValues.contains(neededValue)) {
                pairs.add(new Pair(Math.min(neededValue, current.data),
                                   Math.max(neededValue, current.data)));
            }
 
            visitedValues.add(current.data);
            current = current.next;
        }
 
        return pairs;
    }
 
    // Main method to test the XORLinkedList
    public static void main(String[] args) {
        XORLinkedList xorList = new XORLinkedList();
        int x = 17;
 
        // Use insert() to construct the list
        xorList.insert(11);
        xorList.insert(10);
        xorList.insert(9);
        xorList.insert(8);
        xorList.insert(7);
        xorList.insert(6);
        xorList.insert(3);
 
        // Find pairs with the given sum and sort them
        List<Pair> pairs = xorList.findPairsWithSum(x);
        Collections.sort(pairs);
 
        if (pairs.isEmpty()) {
            System.out.println("No pair found");
        } else {
            for (Pair pair : pairs) {
                System.out.println("(" + pair.first + "," + pair.second + ")");
            }
        }
    }
 
    static class Pair implements Comparable<Pair> {
        int first;
        int second;
 
        public Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }
 
        @Override
        public int compareTo(Pair other) {
            if (this.first == other.first) {
                return Integer.compare(this.second, other.second);
            }
            return Integer.compare(this.first, other.first);
        }
    }
}


Python3




class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
    def xor(self, a, b):
        return a if a is not None else b if b is not None and hash((a, b)) != 0 else None
 
 
class XORLinkedList:
    def __init__(self):
        self.head = None
 
    def insert(self, new_data):
        new_node = Node(new_data)
        if self.head is not None:
            new_node.next = self.head
            self.head = new_node
        else:
            self.head = new_node
 
    def find_pairs_with_sum(self, x):
        if self.head is None:
            print("No elements in the list.")
            return []
 
        visited_values = set()
        current = self.head
        pairs = []
 
        while current is not None:
            needed_value = x - current.data
            if needed_value in visited_values:
                pairs.append((min(needed_value, current.data), max(needed_value, current.data)))
 
            visited_values.add(current.data)
            current = current.next
 
        return pairs
 
    def print_pairs(self, pairs):
        pairs.sort()
        if not pairs:
            print("No pair found")
        else:
            for pair in pairs:
                print(f"({pair[0]}, {pair[1]})")
 
 
if __name__ == "__main__":
    xor_list = XORLinkedList()
    x = 17
 
    # Use insert() to construct the list
    xor_list.insert(11)
    xor_list.insert(10)
    xor_list.insert(9)
    xor_list.insert(8)
    xor_list.insert(7)
    xor_list.insert(6)
    xor_list.insert(3)
 
    # Find pairs with the given sum and print them
    pairs = xor_list.find_pairs_with_sum(x)
    xor_list.print_pairs(pairs)


C#




using System;
using System.Collections.Generic;
 
// Class representing a Node in the XOR Doubly Linked List
class Node {
    public int data;
    public Node next;
 
    // Constructor to create a new Node with data
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
 
    // Function to compute the XOR of two Nodes
    public Node XOR(Node a, Node b)
    {
        return a != null
            ? (b != null
                   ? (object.ReferenceEquals(a, b) ? null
                                                   : this)
                   : a)
            : b;
    }
}
 
public class XORLinkedList {
    // Head of the XOR Doubly Linked List
    private Node head;
 
    // Constructor to initialize an empty list
    public XORLinkedList() { this.head = null; }
 
    // Function to insert a new Node with data at the
    // beginning of the list
    public void Insert(int newData)
    {
        Node newNode = new Node(newData);
        if (head != null) {
            newNode.next = head;
            head = newNode;
        }
        else {
            head = newNode;
        }
    }
 
    // Function to find pairs in the list whose sum is equal
    // to a given value
    public List<Pair> FindPairsWithSum(int x)
    {
        if (head == null) {
            Console.WriteLine("No elements in the list.");
            return new List<Pair>();
        }
 
        HashSet<int> visitedValues = new HashSet<int>();
        Node current = head;
        List<Pair> pairs = new List<Pair>();
 
        while (current != null) {
            int neededValue = x - current.data;
            if (visitedValues.Contains(neededValue)) {
                pairs.Add(new Pair(
                    Math.Min(neededValue, current.data),
                    Math.Max(neededValue, current.data)));
            }
 
            visitedValues.Add(current.data);
            current = current.next;
        }
 
        return pairs;
    }
 
    // Main method to test the XORLinkedList
    public static void Main()
    {
        XORLinkedList xorList = new XORLinkedList();
        int x = 17;
 
        // Use Insert() to construct the list
        xorList.Insert(11);
        xorList.Insert(10);
        xorList.Insert(9);
        xorList.Insert(8);
        xorList.Insert(7);
        xorList.Insert(6);
        xorList.Insert(3);
 
        // Find pairs with the given sum and sort them
        List<Pair> pairs = xorList.FindPairsWithSum(x);
        pairs.Sort();
 
        if (pairs.Count == 0) {
            Console.WriteLine("No pair found");
        }
        else {
            foreach(Pair pair in pairs)
            {
                Console.WriteLine("(" + pair.First + ","
                                  + pair.Second + ")");
            }
        }
    }
 
    // Class representing a Pair of integers
    public class Pair : IComparable<Pair> {
        public int First;
        public int Second;
 
        public Pair(int first, int second)
        {
            this.First = first;
            this.Second = second;
        }
 
        // Implementing the IComparable interface for
        // sorting
        public int CompareTo(Pair other)
        {
            if (this.First == other.First) {
                return this.Second.CompareTo(other.Second);
            }
            return this.First.CompareTo(other.First);
        }
    }
}


Javascript




// Class representing a Node in the XOR Doubly Linked List
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
 
    // Function to compute the XOR of two Nodes
    xor(a, b) {
        return a !== null ? (b !== null ? (a ^ b) : a) : b;
    }
}
 
class XORLinkedList {
    // Constructor to initialize an empty list
    constructor() {
        this.head = null;
    }
 
    // Function to insert a new Node with data at the beginning of the list
    insert(newData) {
        const newNode = new Node(newData);
        if (this.head !== null) {
            newNode.next = this.head;
            this.head = newNode;
        } else {
            this.head = newNode;
        }
    }
 
    // Function to find pairs in the list whose sum is equal to a given value
    findPairsWithSum(x) {
        if (this.head === null) {
            console.log("No elements in the list.");
            return [];
        }
 
        const visitedValues = new Set();
        let current = this.head;
        const pairs = [];
 
        while (current !== null) {
            const neededValue = x - current.data;
            if (visitedValues.has(neededValue)) {
                pairs.push({
                    first: Math.min(neededValue, current.data),
                    second: Math.max(neededValue, current.data)
                });
            }
 
            visitedValues.add(current.data);
            current = current.next;
        }
 
        return pairs;
    }
 
    // Main method to test the XORLinkedList
    static main() {
        const xorList = new XORLinkedList();
        const x = 17;
 
        // Use insert() to construct the list
        xorList.insert(11);
        xorList.insert(10);
        xorList.insert(9);
        xorList.insert(8);
        xorList.insert(7);
        xorList.insert(6);
        xorList.insert(3);
 
        // Find pairs with the given sum and sort them
        const pairs = xorList.findPairsWithSum(x);
        pairs.sort((a, b) => {
            if (a.first === b.first) {
                return a.second - b.second;
            }
            return a.first - b.first;
        });
 
        if (pairs.length === 0) {
            console.log("No pair found");
        } else {
            for (const pair of pairs) {
                console.log(`(${pair.first},${pair.second})`);
            }
        }
    }
}
 
class Pair {
    constructor(first, second) {
        this.first = first;
        this.second = second;
    }
}
 
XORLinkedList.main();


Output: 

(6,11) , (7,10) , (8,9)

Time complexity : O(n)

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.

 



Last Updated : 05 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads