Open In App

Replace each node with its Surpasser Count in Linked List

Given LinkedList, replace each node’s value with its surpasser count. That is the count of elements which are greater towards its right.

Examples: 

Input : 10->12->5->40->21->70->1->49->37->NULL 
Output : 6->5->5->2->3->0->2->0->0->NULL 
Explanation : 
Element in the first node is 10 and the number of elements to the right of the node that are greater than 10 is 6. Therefore replace the node with 6
Element in the first node is 12 and the number of elements to the right of the node that are greater than 12 is 5. Therefore replace the node with 5
Similarly, replace for all the elements in the list.

Input : 5->4->6->3->2->NULL 
Output : 1->1->0->0->0->NULL 

Simple Approach

  1. Take two pointers p and x. The pointer p is used to traverse the list and x is used to traverse the right half of the list for every node.
  2. Initialize a variable count to count the nodes greater than the current nodes.
  3. Traverse through all the nodes in the list using the pointer p. 
    • Initialize the count to 0.
    • Initialize the pointer x to point the current node p.
    • Count the number of nodes that are greater than the current node.
    • Replace the current node with the count.
  4. Repeat step 4 until the list is traversed completely.

Below is the implementation of the above approach:




// C++ program to replace the nodes
// with their surpasser count
 
#include <bits/stdc++.h>
using namespace std;
 
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
 
// Utility function to create a new Node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->next = NULL;
 
    return temp;
}
 
// Function to display the linked list
void printList(Node* node)
{
    while (node != NULL) {
 
        cout << node->data << " ";
 
        node = node->next;
    }
}
 
// Function to check Surpasser Count
void replaceNodes(Node* head)
{
    // Pointer used to traverse through
    // all the nodes in the list
    Node* p = head;
 
    // Pointer used to traverse through the right
    // elements to count the greater elements
    Node* x = NULL;
 
    // Variable to count the number of
    // elements greater than the
    // current element on right
    int count = 0;
 
    int i;
 
    // Traverse through all the elements
    // in the list
    while (p != NULL) {
 
        count = 0;
 
        i = 0;
 
        // Initialize x to current node
        x = p;
 
        // Check or count the number of nodes
        // that are greater than the current
        // node on right
        while (x != NULL) {
 
            if (x->data > p->data)
                count++;
 
            x = x->next;
        }
 
        // Replace the node data with the
        // count of elements greater than
        // the current element
        p->data = count;
        p = p->next;
    }
}
 
// Driver code
int main()
{
    // Creating the linked list
    Node* head = newNode(10);
    head->next = newNode(12);
    head->next->next = newNode(5);
    head->next->next->next = newNode(40);
    head->next->next->next->next = newNode(21);
    head->next->next->next->next->next = newNode(70);
    head->next->next->next->next->next->next = newNode(1);
    head->next->next->next->next->next->next->next = newNode(49);
    head->next->next->next->next->next->next->next->next = newNode(37);
 
    replaceNodes(head);
 
    printList(head);
 
    return 0;
}




// Java program to replace the nodes
// with their surpasser count
 
class GFG {
 
// A linked list node
static class Node {
    int data;
    Node next;
};
  
// Utility function to create a new Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.next = null;
  
    return temp;
}
  
// Function to display the linked list
static void printList(Node node)
{
    while (node != null) {
        System.out.print(node.data+" ");
  
        node = node.next;
    }
}
  
// Function to check Surpasser Count
static void replaceNodes(Node head)
{
    // Pointer used to traverse through
    // all the nodes in the list
    Node p = head;
  
    // Pointer used to traverse through the right
    // elements to count the greater elements
    Node x = null;
  
    // Variable to count the number of
    // elements greater than the
    // current element on right
    int count = 0;
  
    int i;
  
    // Traverse through all the elements
    // in the list
    while (p != null) {
  
        count = 0;
  
        i = 0;
  
        // Initialize x to current node
        x = p;
  
        // Check or count the number of nodes
        // that are greater than the current
        // node on right
        while (x != null) {
  
            if (x.data > p.data)
                count++;
  
            x = x.next;
        }
  
        // Replace the node data with the
        // count of elements greater than
        // the current element
        p.data = count;
        p = p.next;
    }
}
  
// Driver code
public static void main(String[] args) {
  // Creating the linked list
    Node head = newNode(10);
    head.next = newNode(12);
    head.next.next = newNode(5);
    head.next.next.next = newNode(40);
    head.next.next.next.next = newNode(21);
    head.next.next.next.next.next = newNode(70);
    head.next.next.next.next.next.next = newNode(1);
    head.next.next.next.next.next.next.next = newNode(49);
    head.next.next.next.next.next.next.next.next = newNode(37);
  
    replaceNodes(head);
  
    printList(head);
    }
}
 
// This code has been contributed by 29AjayKumar




# Python3 program to replace the nodes
# with their surpasser count
 
# A linked list node
class Node:
     
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to display the linked list
def printList(node):
 
    while node != None:
        print(node.data, end = " ")
        node = node.next
     
# Function to check Surpasser Count
def replaceNodes(head):
 
    # Pointer used to traverse through
    # all the nodes in the list
    p = head
 
    # Pointer used to traverse through
    # the right elements to count the
    # greater elements
    x = None
 
    # Variable to count the number of
    # elements greater than the
    # current element on right
    count = 0
 
    # Traverse through all the elements
    # in the list
    while p != None:
 
        count = 0
 
        # Initialize x to current node
        x = p
 
        # Check or count the number of nodes
        # that are greater than the current
        # node on right
        while x != None:
 
            if x.data > p.data:
                count += 1
 
            x = x.next
 
        # Replace the node data with the
        # count of elements greater than
        # the current element
        p.data = count
        p = p.next
 
# Driver code
if __name__ == "__main__":
 
    # Creating the linked list
    head = Node(10)
    head.next = Node(12)
    head.next.next = Node(5)
    head.next.next.next = Node(40)
    head.next.next.next.next = Node(21)
    head.next.next.next.next.next = Node(70)
    head.next.next.next.next.next.next = Node(1)
    head.next.next.next.next.next.next.next = Node(49)
    head.next.next.next.next.next.next.next.next = Node(37)
 
    replaceNodes(head)
 
    printList(head)
 
# This code is contributed by Rituraj Jain




// C# program to replace the nodes
// with their surpasser count
using System;
 
class GFG
{
 
// A linked list node
public class Node
{
    public int data;
    public Node next;
};
 
// Utility function to create a new Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.next = null;
 
    return temp;
}
 
// Function to display the linked list
static void printList(Node node)
{
    while (node != null)
    {
        Console.Write(node.data + " ");
 
        node = node.next;
    }
}
 
// Function to check Surpasser Count
static void replaceNodes(Node head)
{
    // Pointer used to traverse through
    // all the nodes in the list
    Node p = head;
 
    // Pointer used to traverse through the right
    // elements to count the greater elements
    Node x = null;
 
    // Variable to count the number of
    // elements greater than the
    // current element on right
    int count = 0;
 
    int i;
 
    // Traverse through all the elements
    // in the list
    while (p != null)
    {
 
        count = 0;
 
        i = 0;
 
        // Initialize x to current node
        x = p;
 
        // Check or count the number of nodes
        // that are greater than the current
        // node on right
        while (x != null)
        {
 
            if (x.data > p.data)
                count++;
 
            x = x.next;
        }
 
        // Replace the node data with the
        // count of elements greater than
        // the current element
        p.data = count;
        p = p.next;
    }
}
 
// Driver code
public static void Main()
{
    // Creating the linked list
    Node head = newNode(10);
    head.next = newNode(12);
    head.next.next = newNode(5);
    head.next.next.next = newNode(40);
    head.next.next.next.next = newNode(21);
    head.next.next.next.next.next = newNode(70);
    head.next.next.next.next.next.next = newNode(1);
    head.next.next.next.next.next.next.next = newNode(49);
    head.next.next.next.next.next.next.next.next = newNode(37);
 
    replaceNodes(head);
 
    printList(head);
}
}
 
/* This code contributed by PrinciRaj1992 */




<script>
 
// JavaScript program to replace the nodes
// with their surpasser count
 
// A linked list node
class Node {
        constructor() {
                this.data = 0;
                this.next = null;
             }
        }
         
// Utility function to create a new Node
function newNode( data)
{
    var temp = new Node();
    temp.data = data;
    temp.next = null;
 
    return temp;
}
 
// Function to display the linked list
function printList( node)
{
    while (node != null) {
        document.write(node.data+" ");
 
        node = node.next;
    }
}
 
// Function to check Surpasser Count
function replaceNodes( head)
{
    // Pointer used to traverse through
    // all the nodes in the list
    var p = head;
 
    // Pointer used to traverse through the right
    // elements to count the greater elements
    var x = null;
 
    // Variable to count the number of
    // elements greater than the
    // current element on right
    let count = 0;
 
    let i;
 
    // Traverse through all the elements
    // in the list
    while (p != null) {
 
        count = 0;
 
        i = 0;
 
        // Initialize x to current node
        x = p;
 
        // Check or count the number of nodes
        // that are greater than the current
        // node on right
        while (x != null) {
 
            if (x.data > p.data)
                count++;
 
            x = x.next;
        }
 
        // Replace the node data with the
        // count of elements greater than
        // the current element
        p.data = count;
        p = p.next;
    }
}
 
 
// Driver Code
 
// Creating the linked list
var head = newNode(10);
head.next = newNode(12);
head.next.next = newNode(5);
head.next.next.next = newNode(40);
head.next.next.next.next = newNode(21);
head.next.next.next.next.next = newNode(70);
head.next.next.next.next.next.next = newNode(1);
head.next.next.next.next.next.next.next = newNode(49);
head.next.next.next.next.next.next.next.next = newNode(37);
 
replaceNodes(head);
 
printList(head);
 
</script>

Output
6 5 5 2 3 0 2 0 0 

Complexity Analysis:

 Another Approach with PBDS and Hash map

We can list down our requirements and approach to observe and find a solution. Our approach:

  1. Traverse the linked list from backwards (so we do not concern about elements to the left of current)
  2. Store the current element in a sorted data structure (any point of time, elements are sorted in our data structure)
  3. Find total number of elements greater than the current element in our sorted data structure and replace the current element with it

To traverse the linked list backwards, we will use recursion.

We can use PBDS. With PBDS we can find elements strictly smaller than a particular key. With strictly smaller, we can add current element and subtract it from all the elements. So basically: 

Greater elements than current = Total Elements in PBDS – (Query in PBDS to find elements strictly smaller) – (Current element + element equal to current)

PBDS does not allow duplicate elements. But for the counting part, we need duplicate elements. So we will insert a pair in PBDS (first = element, second = index) to make each entry unique. After that, to find total elements equal to the current element, we will use a hash map. In hash map we will store total occurrences of an element (a basic integer to integer map).

NOTE: We can also construct our own data structure that fulfills the current requirements as we stated. Insert for duplicates in sorted order and query for elements just greater than the key. But we will use C++ STL DS to do it in this post.

Implementation:




#include <iostream>
#include <unordered_map>
 
// library for PBS
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
 
// PBDS of pair<int, int>
#define oset tree<pair<int, int>, null_type,less<pair<int, int>>, rb_tree_tag,tree_order_statistics_node_update>
 
using namespace std;
using namespace __gnu_pbds;
 
// Linked list storage
class Node {
    public:
    int value;
    Node* next;
    Node(int value) {
        this->value = value;
        next = NULL;
    }
};
 
/*
 
head => head is the head of the linked list
os => unordered_set or PBDS
mp => Hash map to store count of each element
count => count of element from backwards
 
*/
 
void solve(Node* head, oset& os, unordered_map<int, int>& mp, int& count) {
    if(head == NULL) return;
    solve(head->next, os, mp, count);
    // we first call our recursion and then compute to traverse the linked list backwards on recursion return
    // increment count backwards
    count++;
    // inserting elements into PBDS with indexes starting from backwards
    os.insert({head->value, count});
    // mapping elements to count
    mp[head->value]++;
    // formula: total elements in PBDS - total number of elements equal to current - elements smaller than current
    int numberOfElements = count - mp[head->value] - os.order_of_key({head->value, -1});
    // replace the linked list current element to the number of elements greater than the current
    head->value = numberOfElements;
}
 
void printList(Node* head) {
    while(head) {
        cout << head->value << (head->next ? "->" : "");
        head = head->next;
    }
    cout << "\n";
}
 
int main() {
    Node* head = new Node(43);
    head->next = new Node(65);
    head->next->next = new Node(12);
    head->next->next->next = new Node(46);
    head->next->next->next->next = new Node(68);
    head->next->next->next->next->next = new Node(85);
    head->next->next->next->next->next->next = new Node(59);
    head->next->next->next->next->next->next->next = new Node(85);
    head->next->next->next->next->next->next->next->next = new Node(37);
    oset os;
    unordered_map<int, int> mp;
    int count = 0;
    printList(head);
    solve(head, os, mp, count);
    printList(head);
    return 0;
}

Output
43->65->12->46->68->85->59->85->37
6->3->6->4->2->0->1->0->0

Complexity Analysis:


Article Tags :