Move the Kth Largest Fibonacci Number Node to the End of a Singly Linked List
Last Updated :
04 Jan, 2024
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read