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>using namespace std;Â
// Node structure of singly linked liststruct Node {Â Â Â Â int data;Â Â Â Â Node* next;};Â
// Function to add a new node at the// beginning of the linked listvoid 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;}Â
// Function to print the linked listvoid printList(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 indexint bellNumber(int n){Â Â Â Â int bell[n + 1][n + 1];Â Â Â Â bell[0][0] = 1;Â
    for (int i = 1; i <= n; i++) {        bell[i][0] = bell[i - 1][i - 1];Â
        for (int j = 1; j <= i; j++) {            bell[i][j]                = bell[i - 1][j - 1] + bell[i][j - 1];        }    }Â
    return bell[n][0];}Â
// Function to find the closest Bell number// to a given node valueint closestBell(int n){Â Â Â Â int bellNum = 0;Â Â Â Â while (bellNumber(bellNum) < n) {Â Â Â Â Â Â Â Â bellNum++;Â Â Â Â }Â
    if (bellNum == 0) {        return bellNumber(bellNum);    }    else {        int prev = bellNumber(bellNum - 1);        int curr = bellNumber(bellNum);        return (n - prev < curr - n) ? prev : curr;    }}Â
// Function to replace every node with// its closest Bell numbervoid replaceWithBell(Node* node){Â Â Â Â while (node != NULL) {Â Â Â Â Â Â Â Â node->data = closestBell(node->data);Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â }}Â
// Driver codeint main(){Â Â Â Â 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);Â
    return 0;} |
Java
// Java code for the above approachclass GFG {Â
    // Node structure of singly linked list    static class Node {        int data;        Node next;Â
        Node(int data) {            this.data = data;            this.next = null;        }    }Â
    // Function to add a new node at the    // beginning of the linked list    static void push(Node[] head_ref, int newData) {        Node newNode = new Node(newData);        newNode.next = head_ref[0];        head_ref[0] = newNode;    }Â
    // Function to print the linked list    static void printList(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    static int bellNumber(int n) {        int[][] bell = new int[n + 1][n + 1];        bell[0][0] = 1;Â
        for (int i = 1; i <= n; i++) {            bell[i][0] = bell[i - 1][i - 1];Â
            for (int j = 1; j <= i; j++) {                bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];            }        }Â
        return bell[n][0];    }Â
    // Function to find the closest Bell number    // to a given node value    static int closestBell(int n) {        int bellNum = 0;        while (bellNumber(bellNum) < n) {            bellNum++;        }Â
        if (bellNum == 0) {            return bellNumber(bellNum);        } else {            int prev = bellNumber(bellNum - 1);            int curr = bellNumber(bellNum);            return (n - prev < curr - n) ? prev : curr;        }    }Â
    // Function to replace every node with    // its closest Bell number    static void replaceWithBell(Node node) {        while (node != null) {            node.data = closestBell(node.data);            node = node.next;        }    }Â
    // Driver code    public static void main(String[] args) {        Node[] head = new Node[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
import mathÂ
# Node class for singly linked listclass Node:    def __init__(self, data):        self.data = data        self.next = NoneÂ
# Function to add a new node at the beginning of the linked listdef push(head_ref, new_data):    new_node = Node(new_data)    new_node.next = head_ref    head_ref = new_node    return head_refÂ
# Function to print the linked listdef printList(node):    while node is not None:        print(node.data, end="")        if node.next is not None:            print(" -> ", end="")        node = node.next    print()Â
# Function to find the Bell number at the given indexdef bellNumber(n):Â Â Â Â bell = [[0 for _ in range(n+1)] for _ in range(n+1)]Â Â Â Â bell[0][0] = 1Â
    for i in range(1, n+1):        bell[i][0] = bell[i-1][i-1]Â
        for j in range(1, i+1):            bell[i][j] = bell[i-1][j-1] + bell[i][j-1]Â
    return bell[n][0]Â
# Function to find the closest Bell number to a given node valuedef closestBell(n):Â Â Â Â bellNum = 0Â Â Â Â while bellNumber(bellNum) < n:Â Â Â Â Â Â Â Â bellNum += 1Â
    if bellNum == 0:        return bellNumber(bellNum)    else:        prev = bellNumber(bellNum - 1)        curr = bellNumber(bellNum)        return prev if n - prev < curr - n else currÂ
# Function to replace every node with its closest Bell numberdef replaceWithBell(node):Â Â Â Â while node is not None:Â Â Â Â Â Â Â Â 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#
using System;Â
// Node class for singly linked listclass Node{Â Â Â Â public int data;Â Â Â Â public Node next;Â
    public Node(int data)    {        this.data = data;        this.next = null;    }}Â
class GFG{    // Function to add a new node at the beginning of the linked list    static Node Push(Node head_ref, int new_data)    {        Node new_node = new Node(new_data);        new_node.next = head_ref;        head_ref = new_node;        return head_ref;    }Â
    // Function to print the linked list    static void PrintList(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    static int BellNumber(int n)    {        int[][] bell = new int[n + 1][];        for (int i = 0; i <= n; i++)        {            bell[i] = new int[n + 1];        }        bell[0][0] = 1;Â
        for (int i = 1; i <= n; i++)        {            bell[i][0] = bell[i - 1][i - 1];Â
            for (int j = 1; j <= i; j++)            {                bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];            }        }Â
        return bell[n][0];    }Â
    // Function to find the closest Bell number to a given node value    static int ClosestBell(int n)    {        int bellNum = 0;        while (BellNumber(bellNum) < n)        {            bellNum++;        }Â
        if (bellNum == 0)        {            return BellNumber(bellNum);        }        else        {            int prev = BellNumber(bellNum - 1);            int curr = BellNumber(bellNum);            return (n - prev < curr - n) ? prev : curr;        }    }Â
    // Function to replace every node with its closest Bell number    static void ReplaceWithBell(Node node)    {        while (node != null)        {            node.data = ClosestBell(node.data);            node = node.next;        }    }Â
    // Driver code    static void Main()    {        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 listfunction Node(data) {Â Â Â Â this.data = data;Â Â Â Â this.next = null;}Â
// Function to add a new node at the beginning of the linked listfunction push(head_ref, new_data) {Â Â Â Â var new_node = new Node(new_data);Â Â Â Â new_node.next = head_ref;Â Â Â Â head_ref = new_node;Â Â Â Â return head_ref;}Â
// Function to print the linked listfunction printList(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 indexfunction bellNumber(n) {Â Â Â Â var bell = [];Â Â Â Â for (var i = 0; i <= n; i++) {Â Â Â Â Â Â Â Â bell[i] = [];Â Â Â Â Â Â Â Â for (var j = 0; j <= n; j++) {Â Â Â Â Â Â Â Â Â Â Â Â bell[i][j] = 0;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â bell[0][0] = 1;Â
    for (var i = 1; i <= n; i++) {        bell[i][0] = bell[i - 1][i - 1];Â
        for (var j = 1; j <= i; j++) {            bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];        }    }Â
    return bell[n][0];}Â
// Function to find the closest Bell number to a given node valuefunction closestBell(n) {Â Â Â Â var bellNum = 0;Â Â Â Â while (bellNumber(bellNum) < n) {Â Â Â Â Â Â Â Â bellNum += 1;Â Â Â Â }Â
    if (bellNum == 0) {        return bellNumber(bellNum);    } else {        var prev = bellNumber(bellNum - 1);        var curr = bellNumber(bellNum);        return n - prev < curr - n ? prev : curr;    }}Â
// Function to replace every node with its closest Bell numberfunction replaceWithBell(node) {Â Â Â Â while (node != null) {Â Â Â Â Â Â Â Â node.data = closestBell(node.data);Â Â Â Â Â Â Â Â node = node.next;Â Â Â Â }}Â
// Driver codeÂ
Â
var head = 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>using namespace std;Â
// Node structure of singly linked liststruct Node {Â Â Â Â int data;Â Â Â Â Node* next;};Â
// Function to add a new node at the// beginning of the linked listvoid 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;}Â
// Function to print the linked listvoid printList(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 complexityint bellNumber(int n){      // initialize vectors    vector<int>curr(n + 1 , 0);    vector<int>prev(n + 1 , 0);         //Base case    curr[0] = 1;    prev[0] = 1;Â
    for (int i = 1; i <= n; i++) {        curr[0] = prev[i - 1];Â
        for (int j = 1; j <= i; j++) {            curr[j]                = prev[j - 1] + curr[j - 1];        }        // assigning values to iterate further        prev= curr;    }Â
    return curr[0];}Â
Â
Â
// Function to find the closest Bell number// to a given node valueint closestBell(int n){Â Â Â Â int bellNum = 0;Â Â Â Â while (bellNumber(bellNum) < n) {Â Â Â Â Â Â Â Â bellNum++;Â Â Â Â }Â
    if (bellNum == 0) {        return bellNumber(bellNum);    }    else {        int prev = bellNumber(bellNum - 1);        int curr = bellNumber(bellNum);        return (n - prev < curr - n) ? prev : curr;    }}Â
// Function to replace every node with// its closest Bell numbervoid replaceWithBell(Node* node){Â Â Â Â while (node != NULL) {Â Â Â Â Â Â Â Â node->data = closestBell(node->data);Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â }}Â
// Driver codeint main(){Â Â Â Â 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);Â
    return 0;} |
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 neveropen!
