Find the Kth Largest Tribonacci Number Node in a Singly Linked List
Last Updated :
20 Dec, 2023
Given a singly linked list containing integers, the task is to find the Kth largest Tribonacci number in the linked list.
Note: A Tribonacci number is a series of numbers where each number is the sum of the three preceding numbers.
The Tribonacci Sequence: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768.......
Examples:
Input: 12 -> 4 -> 9 -> 3 -> 0 -> 25 -> 13 -> NULL, K = 2
Output: 4
Explanation: The Tribonacci number Nodes in the given linked list are 4, 0, 13, and the Kth largest is 4.
Input: 144 -> 111 -> 44 -> 81 -> 1 -> 15 -> 149 -> 0 -> NULL, K = 4
Output: 1
Explanation: The Tribonacci number Nodes in the given linked list are 44, 81, 1, 149, 0, and the Kth largest is 1.
Approach: To solve the problem follow the below idea:
The intuition behind this approach is to efficiently find the Kth largest Tribonacci number in a linked list by maintaining a min-heap (priority queue) of size K. We traverse the linked list, checking each node to see if it is a Tribonacci number. If it is, we compare it with the smallest number in the min-heap. If the current Tribonacci number is larger, we replace the smallest number in the min-heap. This process ensures that the min-heap always contains the K largest Tribonacci numbers encountered in the linked list. As a result, the top element of the min-heap will be the Kth largest Tribonacci number when the traversal is complete.
Steps of this approach:
- Define a priority queue (min-heap) to maintain the K smallest Tribonacci numbers encountered.
- Create a helper function to check if a number is a Tribonacci number by iterating through the Tribonacci sequence.
- Traverse the linked list, examining each node's value.
- For each node, check if it is a Tribonacci number using the helper function.
- If it is a Tribonacci number, add it to the priority queue.
- If the priority queue size exceeds K, remove the smallest element.
- Continue this process until you have processed all nodes in the linked list.
- At the end of the traversal, the priority queue will contain the K largest Tribonacci numbers.
- Return the top element of the priority queue, which represents the Kth largest Tribonacci number.
Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Define the singly linked list node structure
struct ListNode {
int val;
ListNode* next;
ListNode(int x)
: val(x)
, next(nullptr)
{
}
};
// Function to find the Kth largest Tribonacci number
int findKthLargestTribonacci(ListNode* head, int K)
{
// Create a min-heap to keep track of the K smallest
// Tribonacci numbers
priority_queue<int, vector<int>, greater<int> > minHeap;
// Helper function to check if a number is a Tribonacci
// number
auto isTribonacci = [](int num) {
int a = 0, b = 1, c = 1;
while (c <= num) {
if (c == num) {
return true;
}
int temp = a + b + c;
a = b;
b = c;
c = temp;
}
return false;
};
// Traverse the linked list and maintain a min-heap of
// size K
ListNode* current = head;
while (current) {
if (isTribonacci(current->val)) {
minHeap.push(current->val);
// If the min-heap size exceeds K, remove the
// smallest element
if (minHeap.size() > K) {
minHeap.pop();
}
}
current = current->next;
}
// Return the top element of the min-heap, representing
// the Kth largest Tribonacci number
return minHeap
.top(); // Assuming K is always within bounds
}
int main()
{
// Create the first sample linked list
ListNode* head1 = new ListNode(12);
head1->next = new ListNode(4);
head1->next->next = new ListNode(9);
head1->next->next->next = new ListNode(3);
head1->next->next->next->next = new ListNode(0);
head1->next->next->next->next->next = new ListNode(25);
head1->next->next->next->next->next->next
= new ListNode(13);
int K1 = 2;
int result1 = findKthLargestTribonacci(head1, K1);
cout << "The " << K1
<< "th largest Tribonacci number is: " << result1
<< endl;
// Create the second sample linked list
ListNode* head2 = new ListNode(144);
head2->next = new ListNode(111);
head2->next->next = new ListNode(44);
head2->next->next->next = new ListNode(81);
head2->next->next->next->next = new ListNode(1);
head2->next->next->next->next->next = new ListNode(15);
head2->next->next->next->next->next->next
= new ListNode(149);
head2->next->next->next->next->next->next->next
= new ListNode(0);
int K2 = 4;
int result2 = findKthLargestTribonacci(head2, K2);
cout << "The " << K2
<< "th largest Tribonacci number is: " << result2
<< endl;
return 0;
}
Java
import java.util.PriorityQueue;
// Define the singly linked list node structure
class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
next = null;
}
}
public class TribonacciLinkedList {
// Function to find the Kth largest Tribonacci number
public static int findKthLargestTribonacci(ListNode head, int K) {
// Create a min-heap to keep track of the K smallest Tribonacci numbers
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Helper function to check if a number is a Tribonacci number
// The lambda expression (isTribonacci) is used as a predicate
// to test if a given number is a Tribonacci number
// The predicate is used later in the code to filter Tribonacci numbers
java.util.function.Predicate<Integer> isTribonacci = num -> {
int a = 0, b = 1, c = 1;
while (c <= num) {
if (c == num) {
return true;
}
int temp = a + b + c;
a = b;
b = c;
c = temp;
}
return false;
};
// Traverse the linked list and maintain a min-heap of size K
ListNode current = head;
while (current != null) {
if (isTribonacci.test(current.val)) {
minHeap.add(current.val);
// If the min-heap size exceeds K, remove the smallest element
if (minHeap.size() > K) {
minHeap.poll();
}
}
current = current.next;
}
// Return the top element of the min-heap, representing the Kth largest Tribonacci number
return minHeap.peek(); // Assuming K is always within bounds
}
public static void main(String[] args) {
// Create the first sample linked list
ListNode head1 = new ListNode(12);
head1.next = new ListNode(4);
head1.next.next = new ListNode(9);
head1.next.next.next = new ListNode(3);
head1.next.next.next.next = new ListNode(0);
head1.next.next.next.next.next = new ListNode(25);
head1.next.next.next.next.next.next = new ListNode(13);
int K1 = 2;
int result1 = findKthLargestTribonacci(head1, K1);
System.out.println("The " + K1 + "th largest Tribonacci number is: " + result1);
// Create the second sample linked list
ListNode head2 = new ListNode(144);
head2.next = new ListNode(111);
head2.next.next = new ListNode(44);
head2.next.next.next = new ListNode(81);
head2.next.next.next.next = new ListNode(1);
head2.next.next.next.next.next = new ListNode(15);
head2.next.next.next.next.next.next = new ListNode(149);
head2.next.next.next.next.next.next.next = new ListNode(0);
int K2 = 4;
int result2 = findKthLargestTribonacci(head2, K2);
System.out.println("The " + K2 + "th largest Tribonacci number is: " + result2);
}
}
Python3
import heapq
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def find_kth_largest_tribonacci(head, K):
min_heap = []
def is_tribonacci(num):
a, b, c = 0, 1, 1
while c <= num:
if c == num:
return True
temp = a + b + c
a, b, c = b, c, temp
return False
current = head
while current:
if is_tribonacci(current.val):
heapq.heappush(min_heap, current.val)
if len(min_heap) > K:
heapq.heappop(min_heap)
current = current.next
return min_heap[0] if min_heap else None
if __name__ == "__main__":
# Create the first sample linked list
head1 = ListNode(12)
head1.next = ListNode(4)
head1.next.next = ListNode(9)
head1.next.next.next = ListNode(3)
head1.next.next.next.next = ListNode(0)
head1.next.next.next.next.next = ListNode(25)
head1.next.next.next.next.next.next = ListNode(13)
K1 = 2
result1 = find_kth_largest_tribonacci(head1, K1)
print(f"The {K1}th largest Tribonacci number is: {result1}")
# Create the second sample linked list
head2 = ListNode(144)
head2.next = ListNode(111)
head2.next.next = ListNode(44)
head2.next.next.next = ListNode(81)
head2.next.next.next.next = ListNode(1)
head2.next.next.next.next.next = ListNode(15)
head2.next.next.next.next.next.next = ListNode(149)
head2.next.next.next.next.next.next.next = ListNode(0)
K2 = 4
result2 = find_kth_largest_tribonacci(head2, K2)
print(f"The {K2}th largest Tribonacci number is: {result2}")
# code is contributed by shinjanpatra
C#
using System;
using System.Collections.Generic;
// Define the singly linked list node structure
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
class Program
{
// Function to find the Kth largest Tribonacci number
static int FindKthLargestTribonacci(ListNode head, int K)
{
// Create a min-heap to keep track of the K smallest
// Tribonacci numbers
var minHeap = new SortedSet<int>();
// Helper function to check if a number is a Tribonacci
// number
Func<int, bool> isTribonacci = num =>
{
int a = 0, b = 1, c = 1;
while (c <= num)
{
if (c == num)
return true;
int temp = a + b + c;
a = b;
b = c;
c = temp;
}
return false;
};
// Traverse the linked list and maintain a min-heap of
// size K
ListNode current = head;
while (current != null)
{
if (isTribonacci(current.val))
{
minHeap.Add(current.val);
// If the min-heap size exceeds K, remove the
// smallest element
if (minHeap.Count > K)
minHeap.Remove(minHeap.Min);
}
current = current.next;
}
// Return the top element of the min-heap, representing
// the Kth largest Tribonacci number
return minHeap.Min; // Assuming K is always within bounds
}
static void Main()
{
// Create the first sample linked list
ListNode head1 = new ListNode(12)
{
next = new ListNode(4)
{
next = new ListNode(9)
{
next = new ListNode(3)
{
next = new ListNode(0)
{
next = new ListNode(25)
{
next = new ListNode(13)
}
}
}
}
}
};
int K1 = 2;
int result1 = FindKthLargestTribonacci(head1, K1);
Console.WriteLine($"The {K1}th largest Tribonacci number is: {result1}");
// Create the second sample linked list
ListNode head2 = new ListNode(144)
{
next = new ListNode(111)
{
next = new ListNode(44)
{
next = new ListNode(81)
{
next = new ListNode(1)
{
next = new ListNode(15)
{
next = new ListNode(149)
{
next = new ListNode(0)
}
}
}
}
}
}
};
int K2 = 4;
int result2 = FindKthLargestTribonacci(head2, K2);
Console.WriteLine($"The {K2}th largest Tribonacci number is: {result2}");
}
}
JavaScript
// Define the singly linked list node structure
class ListNode {
constructor(x) {
this.val = x;
this.next = null;
}
}
// Function to find the Kth largest Tribonacci number
function findKthLargestTribonacci(head, K) {
// Create a min-heap to keep track of the K smallest Tribonacci numbers
const minHeap = new Set();
// Helper function to check if a number is a Tribonacci number
const isTribonacci = (num) => {
let a = 0, b = 1, c = 1;
while (c <= num) {
if (c === num) {
return true;
}
const temp = a + b + c;
a = b;
b = c;
c = temp;
}
return false;
};
// Traverse the linked list and maintain a min-heap of size K
let current = head;
while (current !== null) {
if (isTribonacci(current.val)) {
minHeap.add(current.val);
// If the min-heap size exceeds K, remove the smallest element
if (minHeap.size > K) {
const minValue = Math.min(...minHeap);
minHeap.delete(minValue);
}
}
current = current.next;
}
// Return the smallest element in the min-heap, representing the Kth largest Tribonacci number
return Math.min(...minHeap); // Assuming K is always within bounds
}
// Create the first sample linked list
const head1 = new ListNode(12);
head1.next = new ListNode(4);
head1.next.next = new ListNode(9);
head1.next.next.next = new ListNode(3);
head1.next.next.next.next = new ListNode(0);
head1.next.next.next.next.next = new ListNode(25);
head1.next.next.next.next.next.next = new ListNode(13);
const K1 = 2;
const result1 = findKthLargestTribonacci(head1, K1);
console.log(`The ${K1}th largest Tribonacci number is: ${result1}`);
// Create the second sample linked list
const head2 = new ListNode(144);
head2.next = new ListNode(111);
head2.next.next = new ListNode(44);
head2.next.next.next = new ListNode(81);
head2.next.next.next.next = new ListNode(1);
head2.next.next.next.next.next = new ListNode(15);
head2.next.next.next.next.next.next = new ListNode(149);
head2.next.next.next.next.next.next.next = new ListNode(0);
const K2 = 4;
const result2 = findKthLargestTribonacci(head2, K2);
console.log(`The ${K2}th largest Tribonacci number is: ${result2}`);
OutputThe 2th largest Tribonacci number is: 4
The 4th largest Tribonacci number is: 1
Time Complexity: O(n*log K), It's linear in the number of nodes (n) in the linked list, but the min-heap operations have a logarithmic time complexity in terms of K.
Auxiliary Space: O(K), The code uses a min-heap with a maximum size of K, and the space required depends on K, which is a constant space requirement.
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
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
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
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
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
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
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
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
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read