Open In App

Product of nodes with Bell Number weights in a Singly Linked List

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list containing nodes with numeric values and their corresponding weights. The goal is to find the product of the nodes whose weight corresponds Bell Number.

Bell numbers are a sequence of numbers that count different combinatorial arrangements, particularly the partitions of a set. These numbers are named after Eric Temple Bell, a prominent mathematician.

Bell numbers have various applications in combinatorics, including counting the number of ways to:

  • Divide a set into non-empty, disjoint subsets.
  • Partition a set into subsets with a specified number of elements.
  • Calculate the number of equivalence relations on a set.
  • Enumerate restricted permutations and many other combinatorial problems.

The first few Bell numbers are 1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, …

Examples:

Input: 12 (4) -> 23 (1) -> 4 (8) -> 14 (52) -> NULL
Output: 322
Explanation: In this example, the nodes with weights that are Bell Numbers are 23 (1) and 14 (52). Their product is 23 * 14 = 322.

Input: 4 (9) -> 5 (1) -> 26 (5) -> 1 (12) -> 56 (203) -> NULL
Output: 7280
Explanation: In this example, the nodes with weights that are Bell Numbers are 5 (1), 26 (5), and 56 (203). Their product is 5 * 26 * 56 = 7280.

Approach: To solve the problem follow the below idea:

In this approach, we aim to find the product of nodes in a singly linked list whose weights correspond to Bell Numbers. To achieve this, we start by dynamically calculating Bell Numbers using a two-dimensional array based on the maximum weight in the linked list. Then, we traverse the list and for each node, we check if its weight matches any Bell Number by comparing it with the values in the Bell Number array. If there’s a match, we multiply the node’s value with the running product. This approach ensures that we consider all nodes with weights as Bell Numbers and accumulate their values to calculate the final product efficiently.

Steps of this approach:

  • Define a function productOfBellNumbers to calculate the product of nodes with weights corresponding to Bell Numbers.
  • Initialize a product variable to 1 to accumulate the result.
  • Traverse the linked list to find the maximum weight, which will determine the size of the Bell Number array.
  • Create a two-dimensional array bell to store Bell Numbers using dynamic programming.
  • Calculate Bell Numbers for weights up to the maximum weight using nested loops.
  • Re-traverse the linked list and for each node, check if its weight matches any Bell Number in the bell array.
  • If a match is found, multiply the node’s value with the running product.
  • Continue this process for all nodes in the linked list.
  • Return the final product, which represents the product of nodes with Bell Number weights.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <iostream>
 
using namespace std;
 
// Define the structure of a singly
// linked list node
struct Node {
    int value;
    int weight;
    Node* next;
 
    Node(int val, int w)
        : value(val)
        , weight(w)
        , next(nullptr)
    {
    }
};
 
// Function to find the product of nodes
// with Bell Number weights
int productOfBellNumbers(Node* head)
{
    int product = 1;
    Node* current = head;
 
    // Step 1: Find the maximum weight in
    // the linked list
    int maxWeight = 0;
    while (current) {
        if (current->weight > maxWeight) {
            maxWeight = current->weight;
        }
        current = current->next;
    }
 
    // Step 2: Calculate Bell Numbers using
    // dynamic programming
    int bell[maxWeight + 1][maxWeight + 1];
    bell[0][0] = 1;
 
    for (int i = 1; i <= maxWeight; 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];
        }
    }
 
    // Step 3: Calculate the product of nodes
    // with Bell Number weights
    current = head;
    while (current) {
        int weight = current->weight;
 
        // Check if the weight is a Bell Number
        for (int i = 0; i <= weight; i++) {
            if (bell[i][0] == weight) {
                product *= current->value;
                break;
            }
        }
        current = current->next;
    }
 
    return product;
}
 
// Function to print the linked list
void printLinkedList(Node* head)
{
    Node* current = head;
    while (current) {
        cout << current->value << " (" << current->weight
             << ") -> ";
        current = current->next;
    }
    cout << "NULL" << endl;
}
 
// Drivers code
int main()
{
    // Create the first linked list
    Node* head1 = new Node(12, 4);
    head1->next = new Node(23, 1);
    head1->next->next = new Node(4, 8);
    head1->next->next->next = new Node(14, 52);
 
    // Calculate and print the product of nodes
    // with Bell Number weights for the first example
    int result1 = productOfBellNumbers(head1);
    cout << "Output 1: " << result1 << endl;
 
    // Free the memory of the first linked list
    while (head1) {
        Node* temp = head1;
        head1 = head1->next;
        delete temp;
    }
 
    // Create the second linked list
    Node* head2 = new Node(4, 9);
    head2->next = new Node(5, 1);
    head2->next->next = new Node(26, 5);
    head2->next->next->next = new Node(1, 12);
    head2->next->next->next->next = new Node(56, 203);
 
    // Calculate and print the product of nodes
    // with Bell Number weights for the second example
    int result2 = productOfBellNumbers(head2);
    cout << "Output 2: " << result2 << endl;
 
    // Free the memory of the second linked list
    while (head2) {
        Node* temp = head2;
        head2 = head2->next;
        delete temp;
    }
 
    return 0;
}


Java




// Java code to implement above approach
 
class Node {
    int value;
    int weight;
    Node next;
 
    Node(int val, int w)
    {
        value = val;
        weight = w;
        next = null;
    }
}
 
public class Main {
    // Function to find the product of nodes with Bell
    // Number weights
    static int productOfBellNumbers(Node head)
    {
        int product = 1;
        Node current = head;
 
        // Step 1: Find the maximum weight in the linked
        // list
        int maxWeight = 0;
        while (current != null) {
            if (current.weight > maxWeight) {
                maxWeight = current.weight;
            }
            current = current.next;
        }
 
        // Step 2: Calculate Bell Numbers using dynamic
        // programming
        int[][] bell
            = new int[maxWeight + 1][maxWeight + 1];
        bell[0][0] = 1;
 
        for (int i = 1; i <= maxWeight; 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];
            }
        }
 
        // Step 3: Calculate the product of nodes with Bell
        // Number weights
        current = head;
        while (current != null) {
            int weight = current.weight;
 
            // Check if the weight is a Bell Number
            for (int i = 0; i <= weight; i++) {
                if (bell[i][0] == weight) {
                    product *= current.value;
                    break;
                }
            }
            current = current.next;
        }
 
        return product;
    }
 
    // Function to print the linked list
    static void printLinkedList(Node head)
    {
        Node current = head;
        while (current != null) {
            System.out.print(current.value + " ("
                             + current.weight + ") -> ");
            current = current.next;
        }
        System.out.println("NULL");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Create the first linked list
        Node head1 = new Node(12, 4);
        head1.next = new Node(23, 1);
        head1.next.next = new Node(4, 8);
        head1.next.next.next = new Node(14, 52);
 
        // Calculate and print the product of nodes with
        // Bell Number weights for the first example
        int result1 = productOfBellNumbers(head1);
        System.out.println("Output 1: " + result1);
 
        // Free the memory of the first linked list
        while (head1 != null) {
            Node temp = head1;
            head1 = head1.next;
            temp.next = null;
        }
 
        // Create the second linked list
        Node head2 = new Node(4, 9);
        head2.next = new Node(5, 1);
        head2.next.next = new Node(26, 5);
        head2.next.next.next = new Node(1, 12);
        head2.next.next.next.next = new Node(56, 203);
 
        // Calculate and print the product of nodes with
        // Bell Number weights for the second example
        int result2 = productOfBellNumbers(head2);
        System.out.println("Output 2: " + result2);
 
        // Free the memory of the second linked list
        while (head2 != null) {
            Node temp = head2;
            head2 = head2.next;
            temp.next = null;
        }
    }
}
 
// This code is contributed by Abhinav Mahajan (abhinav_m22)


Python3




# Define the structure of a singly
# linked list node
 
 
class Node:
    def __init__(self, value, weight):
        self.value = value
        self.weight = weight
        self.next = None
 
# Function to find the product of nodes
# with Bell Number weights
 
 
def product_of_bell_numbers(head):
    product = 1
    current = head
 
    # Step 1: Find the maximum weight in
    # the linked list
    maxWeight = 0
    while current:
        if current.weight > maxWeight:
            maxWeight = current.weight
        current = current.next
 
    # Step 2: Calculate Bell Numbers using dynamic programming
    bell = [[0] * (maxWeight + 1) for _ in range(maxWeight + 1)]
    bell[0][0] = 1
 
    for i in range(1, maxWeight + 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]
 
    # Step 3: Calculate the product of nodes with Bell Number weights
    current = head
    while current:
        weight = current.weight
 
        # Check if the weight is a Bell Number
        for i in range(weight + 1):
            if bell[i][0] == weight:
                product *= current.value
                break
        current = current.next
 
    return product
 
# Function to print the linked list
 
 
def print_linked_list(head):
    current = head
    while current:
        print(f"{current.value} ({current.weight}) -> ", end="")
        current = current.next
    print("NULL")
 
 
# Driver code
if __name__ == "__main__":
    # Create the first linked list
    head1 = Node(12, 4)
    head1.next = Node(23, 1)
    head1.next.next = Node(4, 8)
    head1.next.next.next = Node(14, 52)
 
    # Calculate and print the product of nodes
    # with Bell Number weights for the first example
    result1 = product_of_bell_numbers(head1)
    print("Output 1:", result1)
 
    # Free the memory of the first linked list
    while head1:
        temp = head1
        head1 = head1.next
        temp.next = None
 
    # Create the second linked list
    head2 = Node(4, 9)
    head2.next = Node(5, 1)
    head2.next.next = Node(26, 5)
    head2.next.next.next = Node(1, 12)
    head2.next.next.next.next = Node(56, 203)
 
    # Calculate and print the product of nodes
    # with Bell Number weights for the second example
    result2 = product_of_bell_numbers(head2)
    print("Output 2:", result2)
 
    # Free the memory of the second linked list
    while head2:
        temp = head2
        head2 = head2.next
        temp.next = None


C#




// code by Flutterfly
using System;
 
// Define the structure of a singly
// linked list node
public class Node
{
    public int Value { get; set; }
    public int Weight { get; set; }
    public Node Next { get; set; }
 
    public Node(int val, int w)
    {
        Value = val;
        Weight = w;
        Next = null;
    }
}
 
public class Program
{
    // Function to find the product of nodes
    // with Bell Number weights
    public static int ProductOfBellNumbers(Node head)
    {
        int product = 1;
        Node current = head;
 
        // Step 1: Find the maximum weight in
        // the linked list
        int maxWeight = 0;
        while (current != null)
        {
            if (current.Weight > maxWeight)
            {
                maxWeight = current.Weight;
            }
            current = current.Next;
        }
 
        // Step 2: Calculate Bell Numbers using
        // dynamic programming
        int[,] bell = new int[maxWeight + 1, maxWeight + 1];
        bell[0, 0] = 1;
 
        for (int i = 1; i <= maxWeight; 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];
            }
        }
 
        // Step 3: Calculate the product of nodes
        // with Bell Number weights
        current = head;
        while (current != null)
        {
            int weight = current.Weight;
 
            // Check if the weight is a Bell Number
            for (int i = 0; i <= weight; i++)
            {
                if (i < maxWeight + 1 && bell[i, 0] == weight)
                {
                    product *= current.Value;
                    break;
                }
            }
            current = current.Next;
        }
 
        return product;
    }
 
    // Function to print the linked list
    public static void PrintLinkedList(Node head)
    {
        Node current = head;
        while (current != null)
        {
            Console.Write($"{current.Value} ({current.Weight}) -> ");
            current = current.Next;
        }
        Console.WriteLine("NULL");
    }
 
    // Drivers code
    public static void Main()
    {
        // Create the first linked list
        Node head1 = new Node(12, 4);
        head1.Next = new Node(23, 1);
        head1.Next.Next = new Node(4, 8);
        head1.Next.Next.Next = new Node(14, 52);
 
        // Calculate and print the product of nodes
        // with Bell Number weights for the first example
        int result1 = ProductOfBellNumbers(head1);
        Console.WriteLine($"Output 1: {result1}");
 
        // Free the memory of the first linked list
        while (head1 != null)
        {
            Node temp = head1;
            head1 = head1.Next;
            temp.Next = null;
        }
 
        // Create the second linked list
        Node head2 = new Node(4, 9);
        head2.Next = new Node(5, 1);
        head2.Next.Next = new Node(26, 5);
        head2.Next.Next.Next = new Node(1, 12);
        head2.Next.Next.Next.Next = new Node(56, 203);
 
        // Calculate and print the product of nodes
        // with Bell Number weights for the second example
        int result2 = ProductOfBellNumbers(head2);
        Console.WriteLine($"Output 2: {result2}");
 
        // Free the memory of the second linked list
        while (head2 != null)
        {
            Node temp = head2;
            head2 = head2.Next;
            temp.Next = null;
        }
    }
}


Javascript




class Node {
    constructor(val, w) {
        this.value = val;
        this.weight = w;
        this.next = null;
    }
}
 
function productOfBellNumbers(head) {
    let product = 1;
    let current = head;
 
    // Step 1: Find the maximum weight in the linked list
    let maxWeight = 0;
    while (current) {
        if (current.weight > maxWeight) {
            maxWeight = current.weight;
        }
        current = current.next;
    }
 
    // Step 2: Calculate Bell Numbers using dynamic programming
    let bell = new Array(maxWeight + 1).fill(0).map(() => new Array(maxWeight + 1).fill(0));
    bell[0][0] = 1;
 
    for (let i = 1; i <= maxWeight; i++) {
        bell[i][0] = bell[i - 1][i - 1];
 
        for (let j = 1; j <= i; j++) {
            bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];
        }
    }
 
    // Step 3: Calculate the product of nodes with Bell Number weights
    current = head;
    while (current) {
        let weight = current.weight;
 
        // Check if the weight is a Bell Number
        for (let i = 0; i <= weight; i++) {
            if (i < maxWeight + 1 && bell[i][0] === weight) {
                product *= current.value;
                break;
            }
        }
        current = current.next;
    }
 
    return product;
}
 
function printLinkedList(head) {
    let current = head;
    while (current) {
        console.log(`${current.value} (${current.weight}) ->`);
        current = current.next;
    }
    console.log("NULL");
}
 
// Drivers code
// Create the first linked list
let head1 = new Node(12, 4);
head1.next = new Node(23, 1);
head1.next.next = new Node(4, 8);
head1.next.next.next = new Node(14, 52);
 
// Calculate and print the product of nodes with Bell Number weights for the first example
let result1 = productOfBellNumbers(head1);
console.log("Output 1:", result1);
 
// Create the second linked list
let head2 = new Node(4, 9);
head2.next = new Node(5, 1);
head2.next.next = new Node(26, 5);
head2.next.next.next = new Node(1, 12);
head2.next.next.next.next = new Node(56, 203);
 
// Calculate and print the product of nodes with Bell Number weights for the second example
let result2 = productOfBellNumbers(head2);
console.log("Output 2:", result2);


Output

Output 1: 322
Output 2: 7280






Time Complexity: O(n^2), where n is the number of nodes in list.
Auxiliary Space: O(n), where n is the nodes in list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads