Open In App

Move the Kth Largest Fibonacci Number Node to the End of a Singly Linked List

Last Updated : 04 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list containing integer values. The task is to find the Kth largest Fibonacci number within this list and move it to the end of the list.

Examples:

Input: 12 -> 11 -> 0 -> 5 -> 8 -> 13 -> 17 -> 21 -> NULL, K = 3
Output: 12 -> 11 -> 0 -> 5 -> 13 -> 17 -> 21 -> 8 -> NULL
Explanation: The Fibonacci numbers in the list are 0, 5, 8, 13, and 21. The 3rd largest Fibonacci number is 8, which is moved to the end.

Input: 5 -> 4 -> 34 -> 25 -> 1 -> NULL, K = 2
Output: 4 -> 34 -> 25 -> 1 -> 5 -> NULL
Explanation: The Fibonacci numbers in the list are 5 and 34. The 2nd largest Fibonacci number is 5, which is moved to the end.

Approach: To solve the problem follow the below idea:

The approach begins by traversing the linked list to identify Fibonacci numbers and store them in an array. It then checks if there are at least K Fibonacci numbers. If not, it returns the original list. Next, it sorts these Fibonacci numbers in descending order to find the Kth largest. During a second pass of the linked list, it locates the node with the Kth largest Fibonacci number, removes it from its current position, and appends it to the end of the list.

Steps of the approach:

  • Initialize an empty vector fibonacciNumbers to store Fibonacci numbers found in the linked list.
  • Traverse the linked list while keeping track of the Fibonacci numbers. For each node’s value, check if it’s a Fibonacci number by iteratively calculating Fibonacci numbers up to that value.
  • If a Fibonacci number is found, add it to the fibonacciNumbers vector along with its position in the linked list.
  • Check if the number of Fibonacci numbers found is less than K. If so, return the original linked list as there are not enough Fibonacci numbers.
  • Sort the fibonacciNumbers vector in descending order to determine the Kth largest Fibonacci number.
  • Traverse the linked list again to find the node containing the Kth largest Fibonacci number, and remove it from its current position.
  • Append the removed node to the end of the linked list to complete the process.
  • Return the modified linked list as the final output.

Implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int val;
    Node* next;
    Node(int x)
        : val(x)
        , next(nullptr)
    {
    }
};
 
Node* moveKthLargestFibonacciNode(Node* head, int K)
{
    vector<int> fibonacciNumbers;
 
    // Traverse the linked list and identify Fibonacci
    // numbers.
    Node* current = head;
    while (current) {
        int val = current->val;
        int a = 0, b = 1;
        while (b <= val) {
            if (b == val) {
                fibonacciNumbers.push_back(
                    val); // Found a Fibonacci number.
                break;
            }
            int temp = b;
            b = a + b;
            a = temp;
        }
        current = current->next;
    }
 
    // Not enough Fibonacci numbers in the list
    if (fibonacciNumbers.size() < K) {
        return head;
    }
 
    // Sort the Fibonacci numbers in descending order.
    sort(fibonacciNumbers.rbegin(),
         fibonacciNumbers.rend());
 
    // Find the Kth largest Fibonacci number.
    int kthLargestFibonacci = fibonacciNumbers[K - 1];
 
    // Traverse the linked list to find the node with Kth
    // largest Fibonacci number.
    current = head;
    Node* prev = nullptr;
    while (current) {
        if (current->val == kthLargestFibonacci) {
            if (prev) {
                prev->next = current->next;
                current->next = nullptr;
            }
            else {
                head = current->next;
            }
            break;
        }
        prev = current;
        current = current->next;
    }
 
    // Append the node with Kth largest Fibonacci
    // number to the end.
    if (current) {
        current = head;
        if (!current) {
            head = prev = current
                = new Node(kthLargestFibonacci);
        }
        else {
            while (current->next) {
                current = current->next;
            }
            current->next = new Node(kthLargestFibonacci);
        }
    }
 
    return head;
}
 
// Function to print the linked list.
void printList(Node* head)
{
    Node* current = head;
    while (current) {
        cout << current->val << " -> ";
        current = current->next;
    }
    cout << "NULL" << endl;
}
 
// Drivers code
int main()
{
    // Example 1
    Node* head1 = new Node(12);
    head1->next = new Node(11);
    head1->next->next = new Node(0);
    head1->next->next->next = new Node(5);
    head1->next->next->next->next = new Node(8);
    head1->next->next->next->next->next = new Node(13);
    head1->next->next->next->next->next->next
        = new Node(17);
    head1->next->next->next->next->next->next->next
        = new Node(21);
 
    int K1 = 3;
    head1 = moveKthLargestFibonacciNode(head1, K1);
    printList(head1);
 
    // Example 2
    Node* head2 = new Node(5);
    head2->next = new Node(4);
    head2->next->next = new Node(34);
    head2->next->next->next = new Node(25);
    head2->next->next->next->next = new Node(1);
 
    int K2 = 2;
    head2 = moveKthLargestFibonacciNode(head2, K2);
    printList(head2);
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
class Node {
    int val;
    Node next;
 
    Node(int x) {
        val = x;
        next = null;
    }
}
 
public class MoveKthLargestFibonacciNode {
 
    // Function to move the Kth largest Fibonacci number node to the end
    static Node moveKthLargestFibonacciNode(Node head, int K) {
        List<Integer> fibonacciNumbers = new ArrayList<>();
 
        // Traverse the linked list and identify Fibonacci numbers
        Node current = head;
        while (current != null) {
            int val = current.val;
            int a = 0, b = 1;
            while (b <= val) {
                if (b == val) {
                    fibonacciNumbers.add(val); // Found a Fibonacci number
                    break;
                }
                int temp = b;
                b = a + b;
                a = temp;
            }
            current = current.next;
        }
 
        // Not enough Fibonacci numbers in the list
        if (fibonacciNumbers.size() < K) {
            return head;
        }
 
        // Sort the Fibonacci numbers in descending order
        Collections.sort(fibonacciNumbers, Collections.reverseOrder());
 
        // Find the Kth largest Fibonacci number
        int kthLargestFibonacci = fibonacciNumbers.get(K - 1);
 
        // Traverse the linked list to find the node with Kth largest Fibonacci number
        current = head;
        Node prev = null;
        while (current != null) {
            if (current.val == kthLargestFibonacci) {
                if (prev != null) {
                    prev.next = current.next;
                    current.next = null;
                } else {
                    head = current.next;
                }
                break;
            }
            prev = current;
            current = current.next;
        }
 
        // Append the node with Kth largest Fibonacci number to the end
        if (current != null) {
            current = head;
            if (current == null) {
                head = prev = current = new Node(kthLargestFibonacci);
            } else {
                while (current.next != null) {
                    current = current.next;
                }
                current.next = new Node(kthLargestFibonacci);
            }
        }
 
        return head;
    }
 
    // Function to print the linked list
    static void printList(Node head) {
        Node current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("NULL");
    }
 
    // Drivers code
    public static void main(String[] args) {
        // Example 1
        Node head1 = new Node(12);
        head1.next = new Node(11);
        head1.next.next = new Node(0);
        head1.next.next.next = new Node(5);
        head1.next.next.next.next = new Node(8);
        head1.next.next.next.next.next = new Node(13);
        head1.next.next.next.next.next.next = new Node(17);
        head1.next.next.next.next.next.next.next = new Node(21);
 
        int K1 = 3;
        head1 = moveKthLargestFibonacciNode(head1, K1);
        printList(head1);
 
        // Example 2
        Node head2 = new Node(5);
        head2.next = new Node(4);
        head2.next.next = new Node(34);
        head2.next.next.next = new Node(25);
        head2.next.next.next.next = new Node(1);
 
        int K2 = 2;
        head2 = moveKthLargestFibonacciNode(head2, K2);
        printList(head2);
    }
}


Python3




class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
 
def move_kth_largest_fibonacci_node(head, K):
    fibonacci_numbers = []
 
    # Traverse the linked list and identify Fibonacci numbers
    current = head
    while current:
        val = current.val
        a, b = 0, 1
        while b <= val:
            if b == val:
                fibonacci_numbers.append(val)  # Found a Fibonacci number
                break
            temp = b
            b = a + b
            a = temp
        current = current.next
 
    # Not enough Fibonacci numbers in the list
    if len(fibonacci_numbers) < K:
        return head
 
    # Sort the Fibonacci numbers in descending order
    fibonacci_numbers.sort(reverse=True)
 
    # Find the Kth largest Fibonacci number
    kth_largest_fibonacci = fibonacci_numbers[K - 1]
 
    # Traverse the linked list to find the node with Kth largest Fibonacci number
    current = head
    prev = None
    while current:
        if current.val == kth_largest_fibonacci:
            if prev:
                prev.next = current.next
                current.next = None
            else:
                head = current.next
            break
        prev = current
        current = current.next
 
    # Append the node with Kth largest Fibonacci number to the end
    if current:
        current = head
        if not current:
            head = prev = current = Node(kth_largest_fibonacci)
        else:
            while current.next:
                current = current.next
            current.next = Node(kth_largest_fibonacci)
 
    return head
 
 
# Function to print the linked list
def print_list(head):
    current = head
    while current:
        print(current.val, end=" -> ")
        current = current.next
    print("NULL")
 
 
# Drivers code
if __name__ == "__main__":
    # Example 1
    head1 = Node(12)
    head1.next = Node(11)
    head1.next.next = Node(0)
    head1.next.next.next = Node(5)
    head1.next.next.next.next = Node(8)
    head1.next.next.next.next.next = Node(13)
    head1.next.next.next.next.next.next = Node(17)
    head1.next.next.next.next.next.next.next = Node(21)
 
    K1 = 3
    head1 = move_kth_largest_fibonacci_node(head1, K1)
    print_list(head1)
 
    # Example 2
    head2 = Node(5)
    head2.next = Node(4)
    head2.next.next = Node(34)
    head2.next.next.next = Node(25)
    head2.next.next.next.next = Node(1)
 
    K2 = 2
    head2 = move_kth_largest_fibonacci_node(head2, K2)
    print_list(head2)


C#




using System;
using System.Collections.Generic;
 
class Node
{
    public int val;
    public Node next;
 
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
class Program
{
    static Node MoveKthLargestFibonacciNode(Node head, int K)
    {
        List<int> fibonacciNumbers = new List<int>();
 
        // Traverse the linked list and identify Fibonacci numbers.
        Node current = head;
        while (current != null)
        {
            int val = current.val;
            int a = 0, b = 1;
            while (b <= val)
            {
                if (b == val)
                {
                    fibonacciNumbers.Add(val); // Found a Fibonacci number.
                    break;
                }
                int temp = b;
                b = a + b;
                a = temp;
            }
            current = current.next;
        }
 
        // Not enough Fibonacci numbers in the list
        if (fibonacciNumbers.Count < K)
        {
            return head;
        }
 
        // Sort the Fibonacci numbers in descending order.
        fibonacciNumbers.Sort((a, b) => b.CompareTo(a));
 
        // Find the Kth largest Fibonacci number.
        int kthLargestFibonacci = fibonacciNumbers[K - 1];
 
        // Traverse the linked list to find the node with Kth largest Fibonacci number.
        current = head;
        Node prev = null;
        while (current != null)
        {
            if (current.val == kthLargestFibonacci)
            {
                if (prev != null)
                {
                    prev.next = current.next;
                    current.next = null;
                }
                else
                {
                    head = current.next;
                }
                break;
            }
            prev = current;
            current = current.next;
        }
 
        // Append the node with Kth largest Fibonacci number to the end.
        if (current != null)
        {
            current = head;
            if (current == null)
            {
                head = prev = current = new Node(kthLargestFibonacci);
            }
            else
            {
                while (current.next != null)
                {
                    current = current.next;
                }
                current.next = new Node(kthLargestFibonacci);
            }
        }
 
        return head;
    }
 
    // Function to print the linked list.
    static void PrintList(Node head)
    {
        Node current = head;
        while (current != null)
        {
            Console.Write(current.val + " -> ");
            current = current.next;
        }
        Console.WriteLine("NULL");
    }
 
    // Drivers code
    static void Main()
    {
        // Example 1
        Node head1 = new Node(12);
        head1.next = new Node(11);
        head1.next.next = new Node(0);
        head1.next.next.next = new Node(5);
        head1.next.next.next.next = new Node(8);
        head1.next.next.next.next.next = new Node(13);
        head1.next.next.next.next.next.next = new Node(17);
        head1.next.next.next.next.next.next.next = new Node(21);
 
        int K1 = 3;
        head1 = MoveKthLargestFibonacciNode(head1, K1);
        PrintList(head1);
 
        // Example 2
        Node head2 = new Node(5);
        head2.next = new Node(4);
        head2.next.next = new Node(34);
        head2.next.next.next = new Node(25);
        head2.next.next.next.next = new Node(1);
 
        int K2 = 2;
        head2 = MoveKthLargestFibonacciNode(head2, K2);
        PrintList(head2);
    }
}


Javascript




class Node {
    constructor(x) {
        this.val = x;
        this.next = null;
    }
}
 
function moveKthLargestFibonacciNode(head, K) {
    const fibonacciNumbers = [];
 
    // Helper function to check if a number is Fibonacci or not
    function isFibonacci(num) {
        let a = 0, b = 1;
        while (b <= num) {
            if (b === num) {
                return true;
            }
            let temp = b;
            b = a + b;
            a = temp;
        }
        return false;
    }
 
    // Traverse the linked list and identify Fibonacci numbers
    let current = head;
    while (current !== null) {
        if (isFibonacci(current.val)) {
            fibonacciNumbers.push(current.val); // Found a Fibonacci number
        }
        current = current.next;
    }
 
    // Not enough Fibonacci numbers in the list
    if (fibonacciNumbers.length < K) {
        return head;
    }
 
    // Sort the Fibonacci numbers in descending order
    fibonacciNumbers.sort((a, b) => b - a);
 
    // Find the Kth largest Fibonacci number
    const kthLargestFibonacci = fibonacciNumbers[K - 1];
 
    // Traverse the linked list to find the node with Kth largest Fibonacci number
    current = head;
    let prev = null;
    while (current !== null) {
        if (current.val === kthLargestFibonacci) {
            if (prev !== null) {
                prev.next = current.next;
                current.next = null;
            } else {
                head = current.next;
            }
            break;
        }
        prev = current;
        current = current.next;
    }
 
    // Append the node with Kth largest Fibonacci number to the end
    if (current !== null) {
        current = head;
        if (current === null) {
            head = prev = current = new Node(kthLargestFibonacci);
        } else {
            while (current.next !== null) {
                current = current.next;
            }
            current.next = new Node(kthLargestFibonacci);
        }
    }
 
    return head;
}
 
// Function to print the linked list
function printList(head) {
    let current = head;
    while (current !== null) {
        process.stdout.write(current.val + " -> ");
        current = current.next;
    }
    console.log("NULL");
}
 
// Example 1
let head1 = new Node(12);
head1.next = new Node(11);
head1.next.next = new Node(0);
head1.next.next.next = new Node(5);
head1.next.next.next.next = new Node(8);
head1.next.next.next.next.next = new Node(13);
head1.next.next.next.next.next.next = new Node(17);
head1.next.next.next.next.next.next.next = new Node(21);
 
let K1 = 3;
head1 = moveKthLargestFibonacciNode(head1, K1);
printList(head1);
 
// Example 2
let head2 = new Node(5);
head2.next = new Node(4);
head2.next.next = new Node(34);
head2.next.next.next = new Node(25);
head2.next.next.next.next = new Node(1);
 
let K2 = 2;
head2 = moveKthLargestFibonacciNode(head2, K2);
printList(head2);


Output:

12 -> 11 -> 0 -> 5 -> 13 -> 17 -> 21 -> 8 -> NULL
4 -> 34 -> 25 -> 1 -> 5 -> NULL

Time Complexity: O(n + K * log(K)), where K is the number of Fibonacci numbers, and n is the number of nodes in the linked list.
Auxiliary Space: O(K), where K is the number of Fibonacci numbers in the list. As we are using vector to store the Fibonacci numbers.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads