Sum and Product of all Fibonacci Nodes of a Singly Linked List

Given a singly linked list containing N nodes, the task is to find the sum and product of all the nodes from the list whose data value is a Fibonacci number.
Examples:
Input: LL = 15 -> 16 -> 8 -> 6 -> 13Â
Output: Sum = 21, Product = 104Â
Explanation:Â
The list contains 2 fibonacci data values 8 and 13.Â
Therefore:Â
Sum = 8 + 13 = 21Â
Product = 8 * 13 = 104Input: LL = 5 -> 3 -> 4 -> 2 -> 9Â
Output: Sum = 10, Product = 30Â
Explanation:Â
The list contains 3 fibonacci data values 5, 3 and 2.Â
Therefore:Â
Sum = 5 + 3 + 2 = 10Â
Product = 5 * 3 * 2 = 30Â
Approach: The idea is to use hashing to precompute and store the Fibonacci numbers, and then check if a node contains a Fibonacci value in O(1) time.
- Traverse through the entire linked list and obtain the maximum value in the list.
- Now, in order to check for the Fibonacci numbers, build a hash table containing all the Fibonacci numbers less than or equal to the maximum value in the linked list.
- Finally, traverse the nodes of the linked list one by one and check if the node contains Fibonacci numbers as their data value. Find the sum and product of the data of the nodes which are Fibonacci.
Below is the implementation of the above approach:Â
C++
// C++ implementation to find the sum and// product of all of the Fibonacci nodes// in a singly linked listÂ
#include <bits/stdc++.h>Â
using namespace std;Â
// Node of the singly linked liststruct Node {Â Â Â Â int data;Â Â Â Â Node* next;};Â
// Function to insert a node// at the beginning// of the singly Linked Listvoid push(Node** head_ref, int new_data){    // Allocate new node    Node* new_node        = (Node*)malloc(            sizeof(struct Node));Â
    // Insert the data    new_node->data = new_data;Â
    // Link the old list    // to the new node    new_node->next = (*head_ref);Â
    // Move the head to    // point the new node    (*head_ref) = new_node;}Â
// Function that returns// the largest element// from the linked list.int largestElement(    struct Node* head_ref){    // Declare a max variable    // and initialize with INT_MIN    int max = INT_MIN;Â
    Node* head = head_ref;Â
    // Check loop while    // head not equal to NULL    while (head != NULL) {Â
        // If max is less then head->data        // then assign value of head->data        // to max otherwise        // node points to next node.        if (max < head->data)            max = head->data;Â
        head = head->next;    }    return max;}Â
// Function to create a hash table// to check Fibonacci numbersvoid createHash(set<int>& hash,                int maxElement){    // Inserting the first    // two numbers in the hash    int prev = 0, curr = 1;    hash.insert(prev);    hash.insert(curr);Â
    // Loop to add Fibonacci numbers upto    // the maximum element present in the    // linked list    while (curr <= maxElement) {        int temp = curr + prev;        hash.insert(temp);        prev = curr;        curr = temp;    }}Â
// Function to find// the required sum and productvoid sumAndProduct(Node* head_ref){    // Find the largest node value    // in Singly Linked List    int maxEle        = largestElement(head_ref);Â
    // Creating a set containing    // all the fibonacci numbers    // upto the maximum data value    // in the Singly Linked List    set<int> hash;    createHash(hash, maxEle);Â
    int prod = 1;    int sum = 0;Â
    Node* ptr = head_ref;Â
    // Traverse the linked list    while (ptr != NULL) {Â
        // If current node is fibonacci        if (hash.find(ptr->data)            != hash.end()) {Â
            // Find the sum and the product            prod *= ptr->data;            sum += ptr->data;        }Â
        ptr = ptr->next;    }Â
    cout << "Sum = " << sum << endl;    cout << "Product = " << prod;}Â
// Driver codeint main(){Â
    Node* head = NULL;Â
    // Create the linked list    // 15 -> 16 -> 8 -> 6 -> 13    push(&head, 13);    push(&head, 6);    push(&head, 8);    push(&head, 16);    push(&head, 15);Â
    sumAndProduct(head);Â
    return 0;} |
Java
// Java implementation to find the sum and// product of all of the Fibonacci nodes// in a singly linked listimport java.util.*;Â
class GFG{  // Node of the singly linked liststatic class Node {    int data;    Node next;};  // Function to insert a node// at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){    // Allocate new node    Node new_node = new Node();      // Insert the data    new_node.data = new_data;      // Link the old list    // to the new node    new_node.next = head_ref;      // Move the head to    // point the new node    head_ref = new_node;    return head_ref;}  // Function that returns// the largest element// from the linked list.static int largestElement(    Node head_ref){    // Declare a max variable    // and initialize with Integer.MIN_VALUE    int max = Integer.MIN_VALUE;      Node head = head_ref;      // Check loop while    // head not equal to null    while (head != null) {          // If max is less then head.data        // then assign value of head.data        // to max otherwise        // node points to next node.        if (max < head.data)            max = head.data;          head = head.next;    }    return max;}  // Function to create a hash table// to check Fibonacci numbersstatic void createHash(HashSet<Integer> hash,                int maxElement){    // Inserting the first    // two numbers in the hash    int prev = 0, curr = 1;    hash.add(prev);    hash.add(curr);      // Loop to add Fibonacci numbers upto    // the maximum element present in the    // linked list    while (curr <= maxElement) {        int temp = curr + prev;        hash.add(temp);        prev = curr;        curr = temp;    }}  // Function to find// the required sum and productstatic void sumAndProduct(Node head_ref){    // Find the largest node value    // in Singly Linked List    int maxEle        = largestElement(head_ref);      // Creating a set containing    // all the fibonacci numbers    // upto the maximum data value    // in the Singly Linked List    HashSet<Integer> hash = new HashSet<Integer>();    createHash(hash, maxEle);      int prod = 1;    int sum = 0;      Node ptr = head_ref;      // Traverse the linked list    while (ptr != null) {          // If current node is fibonacci        if (hash.contains(ptr.data)) {              // Find the sum and the product            prod *= ptr.data;            sum += ptr.data;        }          ptr = ptr.next;    }      System.out.print("Sum = " + sum +"\n");    System.out.print("Product = " + prod);}  // Driver codepublic static void main(String[] args){      Node head = null;      // Create the linked list    // 15.16.8.6.13    head = push(head, 13);    head = push(head, 6);    head = push(head, 8);    head = push(head, 16);    head = push(head, 15);      sumAndProduct(head);}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation to find the sum and# product of all of the Fibonacci nodes# in a singly linked listimport sysÂ
# Node of the singly linked listclass Node():         def __init__(self, data):                 self.data = data        self.next = NoneÂ
# Function to insert a node# at the beginning of the # singly Linked Listdef push(head_ref, new_data):         # Allocate new node    new_node = Node(new_data)      # Link the old list    # to the new node    new_node.next = head_ref      # Move the head to    # point the new node    head_ref = new_node         return head_refÂ
# Function that returns# the largest element# from the linked list.def largestElement(head_ref):         # Declare a max variable    # and initialize with INT_MIN    max = -sys.maxsize      head = head_ref      # Check loop while    # head not equal to NULL    while (head != None):          # If max is less then head->data        # then assign value of head->data        # to max otherwise        # node points to next node.        if (max < head.data):            max = head.data          head = head.next         return maxÂ
# Function to create a hash table# to check Fibonacci numbersdef createHash(hash, maxElement):Â
    # Inserting the first    # two numbers in the hash    prev = 0    curr = 1         hash.add(prev)    hash.add(curr)      # Loop to add Fibonacci numbers upto    # the maximum element present in the    # linked list    while (curr <= maxElement):        temp = curr + prev        hash.add(temp)        prev = curr        curr = temp             return hash     # Function to find the # required sum and productdef sumAndProduct(head_ref):         # Find the largest node value    # in Singly Linked List    maxEle = largestElement(head_ref)      # Creating a set containing    # all the fibonacci numbers    # upto the maximum data value    # in the Singly Linked List    hash = set()         hash = createHash(hash, maxEle)      prod = 1    sum = 0      ptr = head_ref      # Traverse the linked list    while (ptr != None):          # If current node is fibonacci        if ptr.data in hash:                         # Find the sum and the product            prod *= ptr.data            sum += ptr.data          ptr = ptr.next         print("Sum =", sum)    print("Product =", prod)  # Driver codeif __name__=="__main__":         head = None;      # Create the linked list    # 15 -> 16 -> 8 -> 6 -> 13    head = push(head, 13)    head = push(head, 6)    head = push(head, 8)    head = push(head, 16)    head = push(head, 15)      sumAndProduct(head)  # This code is contributed by rutvik_56 |
C#
// C# implementation to find the sum and// product of all of the Fibonacci nodes// in a singly linked listusing System;using System.Collections.Generic;Â
class GFG{   // Node of the singly linked listclass Node {    public int data;    public Node next;};   // Function to insert a node// at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){    // Allocate new node    Node new_node = new Node();       // Insert the data    new_node.data = new_data;       // Link the old list    // to the new node    new_node.next = head_ref;       // Move the head to    // point the new node    head_ref = new_node;    return head_ref;}   // Function that returns// the largest element// from the linked list.static int largestElement(    Node head_ref){    // Declare a max variable    // and initialize with int.MinValue    int max = int.MinValue;       Node head = head_ref;       // Check loop while    // head not equal to null    while (head != null) {           // If max is less then head.data        // then assign value of head.data        // to max otherwise        // node points to next node.        if (max < head.data)            max = head.data;           head = head.next;    }    return max;}   // Function to create a hash table// to check Fibonacci numbersstatic void createHash(HashSet<int> hash,                int maxElement){    // Inserting the first    // two numbers in the hash    int prev = 0, curr = 1;    hash.Add(prev);    hash.Add(curr);       // Loop to add Fibonacci numbers upto    // the maximum element present in the    // linked list    while (curr <= maxElement) {        int temp = curr + prev;        hash.Add(temp);        prev = curr;        curr = temp;    }}   // Function to find// the required sum and productstatic void sumAndProduct(Node head_ref){    // Find the largest node value    // in Singly Linked List    int maxEle        = largestElement(head_ref);       // Creating a set containing    // all the fibonacci numbers    // upto the maximum data value    // in the Singly Linked List    HashSet<int> hash = new HashSet<int>();    createHash(hash, maxEle);       int prod = 1;    int sum = 0;       Node ptr = head_ref;       // Traverse the linked list    while (ptr != null) {           // If current node is fibonacci        if (hash.Contains(ptr.data)) {               // Find the sum and the product            prod *= ptr.data;            sum += ptr.data;        }           ptr = ptr.next;    }       Console.Write("Sum = " + sum +"\n");    Console.Write("Product = " + prod);}   // Driver codepublic static void Main(String[] args){       Node head = null;       // Create the linked list    // 15.16.8.6.13    head = push(head, 13);    head = push(head, 6);    head = push(head, 8);    head = push(head, 16);    head = push(head, 15);       sumAndProduct(head);}}  // This code is contributed by Princi Singh |
Javascript
<script>// javascript implementation to find the sum and// product of all of the Fibonacci nodes// in a singly linked listÂ
    // Node of the singly linked list    class Node {        constructor() {            this.data = 0;            this.next = null;        }    }Â
    // Function to insert a node    // at the beginning    // of the singly Linked List    function push(head_ref , new_data) {        // Allocate new nodevar new_node = new Node();Â
        // Insert the data        new_node.data = new_data;Â
        // Link the old list        // to the new node        new_node.next = head_ref;Â
        // Move the head to        // point the new node        head_ref = new_node;        return head_ref;    }Â
    // Function that returns    // the largest element    // from the linked list.    function largestElement(head_ref) {        // Declare a max variable        // and initialize with Number.MIN_VALUE        var max = Number.MIN_VALUE;Â
var head = head_ref;Â
        // Check loop while        // head not equal to null        while (head != null) {Â
            // If max is less then head.data            // then assign value of head.data            // to max otherwise            // node points to next node.            if (max < head.data)                max = head.data;Â
            head = head.next;        }        return max;    }Â
    // Function to create a hash table    // to check Fibonacci numbers    function createHash( hash , maxElement) {        // Inserting the first        // two numbers in the hash        var prev = 0, curr = 1;        hash.add(prev);        hash.add(curr);Â
        // Loop to add Fibonacci numbers upto        // the maximum element present in the        // linked list        while (curr <= maxElement) {            var temp = curr + prev;            hash.add(temp);            prev = curr;            curr = temp;        }    }Â
    // Function to find    // the required sum and product    function sumAndProduct(head_ref) {        // Find the largest node value        // in Singly Linked List        var maxEle = largestElement(head_ref);Â
        // Creating a set containing        // all the fibonacci numbers        // upto the maximum data value        // in the Singly Linked List        var hash = new Set();        createHash(hash, maxEle);Â
        var prod = 1;        var sum = 0;Â
var ptr = head_ref;Â
        // Traverse the linked list        while (ptr != null) {Â
            // If current node is fibonacci            if (hash.has(ptr.data)) {Â
                // Find the sum and the product                prod *= ptr.data;                sum += ptr.data;            }Â
            ptr = ptr.next;        }Â
        document.write("Sum = " + sum + "<br/>");        document.write("Product = " + prod);    }Â
    // Driver code     Â
var head = null;Â
        // Create the linked list        // 15.16.8.6.13        head = push(head, 13);        head = push(head, 6);        head = push(head, 8);        head = push(head, 16);        head = push(head, 15);Â
        sumAndProduct(head);Â
// This code contributed by umadevi9616</script> |
Sum = 21 Product = 104
Â
Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1) because it is using constant space
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



