Replace every node in a linked list with its closest bell number

Given a singly linked list, the task is to replace every node with its closest bell number.
Bell numbers are a sequence of numbers that represent the number of partitions of a set. In other words, given a set of n elements, the Bell number for n represents the total number of distinct ways that the set can be partitioned into subsets.
The first few Bell numbers are 1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, …
Examples:
Input: 14 -> 7 -> 190 -> 2 -> 5 -> NULL
Output: 15 -> 5 -> 203 -> 2 -> 5 -> NULL
Explanation: The closest Bell numbers for each node are:
- Node 1 (value = 14): Closest Bell number = 15.
- Node 2 (value = 7): Closest Bell number = 5.
- Node 3 (value = 190): Closest Bell number = 203.
- Node 4 (value = 2): Closest Bell number = 2.
- Node 5 (value = 5): Closest Bell number = 5.
Input: 50 -> 1 -> 4 -> NULL
Output: 52 -> 1 -> 5 -> NULL
Explanation: The closest Bell numbers for each node are:
- Node 1 (value = 50): Closest Bell number = 52.
- Node 1 (value = 1): Closest Bell number = 1.
- Node 1 (value = 4): Closest Bell number = 5.
Approach: This can be solved with the following idea:
The algorithm first calculates the Bell number at a given index by filling a 2D array using a dynamic programming approach. Then, it finds the closest Bell number to a given node value by iterating through the Bell numbers until it finds a Bell number greater than or equal to the node value. It then compares the difference between the previous and current Bell numbers to determine which one is closer to the node value. Finally, it replaces each node in the linked list with its closest Bell number using a while loop that iterates through each node in the linked list.
Steps of the above approach:
- Define a bellNumber function that takes an integer n as an argument and returns the nth Bell number. The function uses dynamic programming to calculate the Bell number.
- Define a closestBell function that takes an integer n as an argument and returns the closest Bell number to n.
- This function iteratively calls the bellNumber function until it finds the smallest Bell number greater than or equal to n.
- If n is less than the first Bell number (which is 1), then the function returns the first Bell number. Otherwise, the function compares the difference between n and the previous Bell number to the difference between the next Bell number and n and returns the closer Bell number.
- Define a replaceWithBell function that takes the head of a linked list as an argument and replaces the data value of each node in the list with the closest Bell number to its original data value.
- The function iterates through each node in the list, calls the closestBell function to find the closest Bell number to the node’s original data value, and assigns that value to the node’s data field.
Below is the implementation of the above approach:
C++
| // C++ code for the above approach:#include <cmath>#include <iostream>usingnamespacestd;// Node structure of singly linked liststructNode {    intdata;    Node* next;};// Function to add a new node at the// beginning of the linked listvoidpush(Node** head_ref, intnew_data){    Node* new_node = newNode;    new_node->data = new_data;    new_node->next = (*head_ref);    (*head_ref) = new_node;}// Function to print the linked listvoidprintList(Node* node){    while(node != NULL) {        cout << node->data;        if(node->next != NULL) {            cout << " -> ";        }        node = node->next;    }}// Function to find the Bell number at// the given indexintbellNumber(intn){    intbell[n + 1][n + 1];    bell[0][0] = 1;    for(inti = 1; i <= n; i++) {        bell[i][0] = bell[i - 1][i - 1];        for(intj = 1; j <= i; j++) {            bell[i][j]                = bell[i - 1][j - 1] + bell[i][j - 1];        }    }    returnbell[n][0];}// Function to find the closest Bell number// to a given node valueintclosestBell(intn){    intbellNum = 0;    while(bellNumber(bellNum) < n) {        bellNum++;    }    if(bellNum == 0) {        returnbellNumber(bellNum);    }    else{        intprev = bellNumber(bellNum - 1);        intcurr = bellNumber(bellNum);        return(n - prev < curr - n) ? prev : curr;    }}// Function to replace every node with// its closest Bell numbervoidreplaceWithBell(Node* node){    while(node != NULL) {        node->data = closestBell(node->data);        node = node->next;    }}// Driver codeintmain(){    Node* head = NULL;    // Creating the linked list    push(&head, 5);    push(&head, 2);    push(&head, 190);    push(&head, 7);    push(&head, 14);    // Function call    replaceWithBell(head);    printList(head);    return0;} | 
Java
| // Java code for the above approachclassGFG {    // Node structure of singly linked list    staticclassNode {        intdata;        Node next;        Node(intdata) {            this.data = data;            this.next = null;        }    }    // Function to add a new node at the    // beginning of the linked list    staticvoidpush(Node[] head_ref, intnewData) {        Node newNode = newNode(newData);        newNode.next = head_ref[0];        head_ref[0] = newNode;    }    // Function to print the linked list    staticvoidprintList(Node node) {        while(node != null) {            System.out.print(node.data);            if(node.next != null) {                System.out.print(" -> ");            }            node = node.next;        }    }    // Function to find the Bell number at    // the given index    staticintbellNumber(intn) {        int[][] bell = newint[n + 1][n + 1];        bell[0][0] = 1;        for(inti = 1; i <= n; i++) {            bell[i][0] = bell[i - 1][i - 1];            for(intj = 1; j <= i; j++) {                bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];            }        }        returnbell[n][0];    }    // Function to find the closest Bell number    // to a given node value    staticintclosestBell(intn) {        intbellNum = 0;        while(bellNumber(bellNum) < n) {            bellNum++;        }        if(bellNum == 0) {            returnbellNumber(bellNum);        } else{            intprev = bellNumber(bellNum - 1);            intcurr = bellNumber(bellNum);            return(n - prev < curr - n) ? prev : curr;        }    }    // Function to replace every node with    // its closest Bell number    staticvoidreplaceWithBell(Node node) {        while(node != null) {            node.data = closestBell(node.data);            node = node.next;        }    }    // Driver code    publicstaticvoidmain(String[] args) {        Node[] head = newNode[1];        // Creating the linked list        push(head, 5);        push(head, 2);        push(head, 190);        push(head, 7);        push(head, 14);        // Function call        replaceWithBell(head[0]);        printList(head[0]);    }}// This code is contributed by shivamgupta310570 | 
Python3
| importmath# Node class for singly linked listclassNode:    def__init__(self, data):        self.data =data        self.next=None# Function to add a new node at the beginning of the linked listdefpush(head_ref, new_data):    new_node =Node(new_data)    new_node.next=head_ref    head_ref =new_node    returnhead_ref# Function to print the linked listdefprintList(node):    whilenode isnotNone:        print(node.data, end="")        ifnode.nextisnotNone:            print(" -> ", end="")        node =node.next    print()# Function to find the Bell number at the given indexdefbellNumber(n):    bell =[[0for_ inrange(n+1)] for_ inrange(n+1)]    bell[0][0] =1    fori inrange(1, n+1):        bell[i][0] =bell[i-1][i-1]        forj inrange(1, i+1):            bell[i][j] =bell[i-1][j-1] +bell[i][j-1]    returnbell[n][0]# Function to find the closest Bell number to a given node valuedefclosestBell(n):    bellNum =0    whilebellNumber(bellNum) < n:        bellNum +=1    ifbellNum ==0:        returnbellNumber(bellNum)    else:        prev =bellNumber(bellNum -1)        curr =bellNumber(bellNum)        returnprev ifn -prev < curr -n elsecurr# Function to replace every node with its closest Bell numberdefreplaceWithBell(node):    whilenode isnotNone:        node.data =closestBell(node.data)        node =node.next# Driver codeif__name__ =="__main__":    head =None    # Creating the linked list    head =push(head, 5)    head =push(head, 2)    head =push(head, 190)    head =push(head, 7)    head =push(head, 14)    # Function call    replaceWithBell(head)    printList(head) | 
C#
| usingSystem;// Node class for singly linked listclassNode{    publicintdata;    publicNode next;    publicNode(intdata)    {        this.data = data;        this.next = null;    }}classGFG{    // Function to add a new node at the beginning of the linked list    staticNode Push(Node head_ref, intnew_data)    {        Node new_node = newNode(new_data);        new_node.next = head_ref;        head_ref = new_node;        returnhead_ref;    }    // Function to print the linked list    staticvoidPrintList(Node node)    {        while(node != null)        {            Console.Write(node.data);            if(node.next != null)            {                Console.Write(" -> ");            }            node = node.next;        }        Console.WriteLine();    }    // Function to find the Bell number at the given index    staticintBellNumber(intn)    {        int[][] bell = newint[n + 1][];        for(inti = 0; i <= n; i++)        {            bell[i] = newint[n + 1];        }        bell[0][0] = 1;        for(inti = 1; i <= n; i++)        {            bell[i][0] = bell[i - 1][i - 1];            for(intj = 1; j <= i; j++)            {                bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];            }        }        returnbell[n][0];    }    // Function to find the closest Bell number to a given node value    staticintClosestBell(intn)    {        intbellNum = 0;        while(BellNumber(bellNum) < n)        {            bellNum++;        }        if(bellNum == 0)        {            returnBellNumber(bellNum);        }        else        {            intprev = BellNumber(bellNum - 1);            intcurr = BellNumber(bellNum);            return(n - prev < curr - n) ? prev : curr;        }    }    // Function to replace every node with its closest Bell number    staticvoidReplaceWithBell(Node node)    {        while(node != null)        {            node.data = ClosestBell(node.data);            node = node.next;        }    }    // Driver code    staticvoidMain()    {        Node head = null;        // Creating the linked list        head = Push(head, 5);        head = Push(head, 2);        head = Push(head, 190);        head = Push(head, 7);        head = Push(head, 14);        // Function call        ReplaceWithBell(head);        PrintList(head);    }} | 
Javascript
| // Javascript Implementation// Node class for singly linked listfunctionNode(data) {    this.data = data;    this.next = null;}// Function to add a new node at the beginning of the linked listfunctionpush(head_ref, new_data) {    varnew_node = newNode(new_data);    new_node.next = head_ref;    head_ref = new_node;    returnhead_ref;}// Function to print the linked listfunctionprintList(node) {    while(node != null) {        console.log(node.data + " ");        if(node.next != null) {           console.log("-> ");        }        node = node.next;    }}// Function to find the Bell number at the given indexfunctionbellNumber(n) {    varbell = [];    for(vari = 0; i <= n; i++) {        bell[i] = [];        for(varj = 0; j <= n; j++) {            bell[i][j] = 0;        }    }    bell[0][0] = 1;    for(vari = 1; i <= n; i++) {        bell[i][0] = bell[i - 1][i - 1];        for(varj = 1; j <= i; j++) {            bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];        }    }    returnbell[n][0];}// Function to find the closest Bell number to a given node valuefunctionclosestBell(n) {    varbellNum = 0;    while(bellNumber(bellNum) < n) {        bellNum += 1;    }    if(bellNum == 0) {        returnbellNumber(bellNum);    } else{        varprev = bellNumber(bellNum - 1);        varcurr = bellNumber(bellNum);        returnn - prev < curr - n ? prev : curr;    }}// Function to replace every node with its closest Bell numberfunctionreplaceWithBell(node) {    while(node != null) {        node.data = closestBell(node.data);        node = node.next;    }}// Driver codevarhead = null;// creating the linked listhead = push(head, 5);head = push(head, 2);head = push(head, 190);head = push(head, 7);head = push(head, 14);// Function callreplaceWithBell(head);printList(head);// This code is contributed by Tapesh(tapeshdua420) | 
15 -> 5 -> 203 -> 2 -> 5
Time Complexity: O(n3)
Auxiliary Space: O(n2)
Efficient approach: Space Optimized solution O(N)
In previous approach we are using 2D array to store the computations of subproblems but the current value is only dependent on the current and previous row of matrix so in this approach we are using 2 vector to store the current and previous rows of matrix.
Implementation steps:
- Initialize 2 vectors curr and prev of size N to store the current and previous rows of matrix.
- Now initialize the base case for n=0.
- Now iterate over subproblems to get the current value from previous computations.
- After every iteration assign values of prev to curr vector.
C++
| // C++ code for the above approach:#include <bits/stdc++.h>usingnamespacestd;// Node structure of singly linked liststructNode {    intdata;    Node* next;};// Function to add a new node at the// beginning of the linked listvoidpush(Node** head_ref, intnew_data){    Node* new_node = newNode;    new_node->data = new_data;    new_node->next = (*head_ref);    (*head_ref) = new_node;}// Function to print the linked listvoidprintList(Node* node){    while(node != NULL) {        cout << node->data;        if(node->next != NULL) {            cout << " -> ";        }        node = node->next;    }}// Function to find the Bell number at// the given index in O(N) space complexityintbellNumber(intn){       // initialize vectors    vector<int>curr(n + 1 , 0);    vector<int>prev(n + 1 , 0);        //Base case    curr[0] = 1;    prev[0] = 1;    for(inti = 1; i <= n; i++) {        curr[0] = prev[i - 1];        for(intj = 1; j <= i; j++) {            curr[j]                = prev[j - 1] + curr[j - 1];        }        // assigning values to iterate further        prev= curr;    }    returncurr[0];}// Function to find the closest Bell number// to a given node valueintclosestBell(intn){    intbellNum = 0;    while(bellNumber(bellNum) < n) {        bellNum++;    }    if(bellNum == 0) {        returnbellNumber(bellNum);    }    else{        intprev = bellNumber(bellNum - 1);        intcurr = bellNumber(bellNum);        return(n - prev < curr - n) ? prev : curr;    }}// Function to replace every node with// its closest Bell numbervoidreplaceWithBell(Node* node){    while(node != NULL) {        node->data = closestBell(node->data);        node = node->next;    }}// Driver codeintmain(){    Node* head = NULL;    // Creating the linked list    push(&head, 5);    push(&head, 2);    push(&head, 190);    push(&head, 7);    push(&head, 14);    // Function call    replaceWithBell(head);    printList(head);    return0;} | 
Time Complexity: O(n^2)
Auxiliary Space: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
 
				 
					


