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 = 104

Input: 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.



  1. Traverse through the entire linked list and obtain the maximum value in the list.
  2. 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.
  3. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 list
struct Node {
    int data;
    Node* next;
};
  
// Function to insert a node
// at the beginning
// of the singly Linked List
void 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 numbers
void 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 product
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
    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 code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the sum and
// product of all of the Fibonacci nodes
// in a singly linked list
import java.util.*;
  
class GFG{
   
// Node of the singly linked list
static class Node {
    int data;
    Node next;
};
   
// Function to insert a node
// at the beginning
// of the singly Linked List
static 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 numbers
static 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 product
static 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 code
public 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the sum and
// product of all of the Fibonacci nodes
// in a singly linked list
using System;
using System.Collections.Generic;
  
class GFG{
    
// Node of the singly linked list
class Node {
    public int data;
    public Node next;
};
    
// Function to insert a node
// at the beginning
// of the singly Linked List
static 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 numbers
static 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 product
static 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 code
public 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

chevron_right


Output:

Sum = 21
Product = 104

Time Complexity: O(N), where N is the number of nodes in the linked list.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, princi singh