Open In App

Replace Linked List nodes with its closest Tribonacci number

Last Updated : 15 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list of integers, the task is to replace every node with its closest Tribonacci number and return the modified linked list.

Examples:

Input: List: 3 -> 5 -> 9 -> 12
Output: 2 -> 4 -> 7 -> 13
Explanation: The closest Tribonacci numbers for each node are:

  • Node 1 (value = 3): Closest Tribonacci number = 2.
  • Node 2 (value = 5): Closest Tribonacci number = 4.
  • Node 3 (value = 9): Closest Tribonacci number = 7.
  • Node 4 (value = 12): Closest Tribonacci number = 13.

Input: List: 2->8->14->5->16
Output: 2->7->13->4->13
Explanation: The closest Tribonacci numbers for each node are:

  • Node 1 (value = 2): Closest Tribonacci number = 2.
  • Node 2 (value = 8): Closest Tribonacci number = 7.
  • Node 3 (value = 14): Closest Tribonacci number = 13.
  • Node 4 (value = 5): Closest Tribonacci number = 4.
  • Node 5 (value = 16): Closest Tribonacci number = 13.

Approach: This can be solved with the following idea:

  • The problem requires us to replace every node in a singly linked list with its closest Tribonacci number. A Tribonacci sequence is a sequence of numbers where each number is the sum of the three preceding numbers, starting with 0, 1, 1. For example, the first few terms of the Tribonacci sequence are: 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, …
  • To solve this problem, we can iterate through the linked list and replace each node’s value with its closest Tribonacci number. We can compute the closest Tribonacci number for a given value by generating the Tribonacci sequence up to the point where the largest Tribonacci number is greater than the given value. Then, we can iterate through the sequence to find the Tribonacci number with the smallest absolute difference from the given value.

Here’s the step-by-step approach:

  • Define a helper function closest_tribonacci(num) that takes an integer num as input and returns the closest Tribonacci number to num.
  • Inside the closest_tribonacci function, generate the Tribonacci sequence up to the point where the largest Tribonacci number is greater than num. We can do this by initializing a vector tribonacci with the first three Tribonacci numbers, then appending the sum of the last three numbers to the vector until the last element is greater than num.
  • Initialize two variables min_diff and closest_trib to the difference between num and the first Tribonacci number in the sequence and the first Tribonacci number, respectively.
  • Iterate through the rest of the Fibonacci sequence and for each element, compute the absolute difference between it and num. If the difference is smaller than min_diff, update min_diff and closest_trib to the new values.
  • Return closest_trib from the closest_tribonacci function.
  • Define a function replaceWithClosestTribonacci(head) that takes the head node of a singly linked list as input and modifies the linked list by replacing each node’s value with its closest Tribonacci number. Iterate through the linked list and for each node, call the closest_tribonacci function to get its closest Tribonacci number, and replace the node’s value with this number.
  • Return the head node of the modified linked list.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Define the linked list node
struct Node {
    int val;
    Node* next;
    Node(int x)
        : val(x), next(nullptr)
    {
    }
};
 
// Helper function to compute the closest
// Tribonacci number
int closest_tribonacci(int num)
{
    vector<int> tribonacci = { 0, 1, 1 };
    while (tribonacci.back() < num) {
        int next_trib = tribonacci[tribonacci.size() - 1]
                        + tribonacci[tribonacci.size() - 2]
                        + tribonacci[tribonacci.size() - 3];
        tribonacci.push_back(next_trib);
    }
    int min_diff = abs(num - tribonacci[0]);
    int closest_trib = tribonacci[0];
    for (int i = 1; i < tribonacci.size(); i++) {
        int diff = abs(num - tribonacci[i]);
        if (diff < min_diff) {
            min_diff = diff;
            closest_trib = tribonacci[i];
        }
    }
    return closest_trib;
}
 
// Function to replace linked list nodes
// with closest Tribonacci numbers
Node* replaceWithClosestTribonacci(Node* head)
{
    Node* curr = head;
    while (curr != nullptr) {
        int closest_trib = closest_tribonacci(curr->val);
        curr->val = closest_trib;
        curr = curr->next;
    }
    return head;
}
 
// Function to print list
void printList(Node* head)
{
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->val << "->";
        curr = curr->next;
    }
    cout << "null" << endl;
}
 
// Driver code
int main()
{
    Node* head = new Node(2);
    head->next = new Node(8);
    head->next->next = new Node(14);
    head->next->next->next = new Node(5);
    head->next->next->next->next = new Node(16);
 
    // Function call
    replaceWithClosestTribonacci(head);
 
    printList(head);
 
    return 0;
}


Java




//Java code for the above approach:
import java.util.ArrayList;
import java.util.List;
 
// Define the linked list node
class Node {
    int val;
    Node next;
 
    Node(int x) {
        val = x;
        next = null;
    }
}
 
public class GFG {
    // Helper function to compute the closest Tribonacci number
    public static int closestTribonacci(int num) {
        List<Integer> tribonacci = new ArrayList<>();
        tribonacci.add(0);
        tribonacci.add(1);
        tribonacci.add(1);
 
        while (tribonacci.get(tribonacci.size() - 1) < num) {
            int nextTrib = tribonacci.get(tribonacci.size() - 1)
                    + tribonacci.get(tribonacci.size() - 2)
                    + tribonacci.get(tribonacci.size() - 3);
            tribonacci.add(nextTrib);
        }
 
        int minDiff = Math.abs(num - tribonacci.get(0));
        int closestTrib = tribonacci.get(0);
 
        for (int i = 1; i < tribonacci.size(); i++) {
            int diff = Math.abs(num - tribonacci.get(i));
            if (diff < minDiff) {
                minDiff = diff;
                closestTrib = tribonacci.get(i);
            }
        }
 
        return closestTrib;
    }
 
    // Function to replace linked list nodes with closest Tribonacci numbers
    public static Node replaceWithClosestTribonacci(Node head) {
        Node curr = head;
 
        while (curr != null) {
            int closestTrib = closestTribonacci(curr.val);
            curr.val = closestTrib;
            curr = curr.next;
        }
 
        return head;
    }
 
    // Function to print list
    public static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.val + "->");
            curr = curr.next;
        }
        System.out.println("null");
    }
 
    // Driver code
    public static void main(String[] args) {
        Node head = new Node(2);
        head.next = new Node(8);
        head.next.next = new Node(14);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(16);
 
        // Function call to replace values with closest Tribonacci numbers
        replaceWithClosestTribonacci(head);
 
        // Print the modified linked list
        printList(head);
    }
}


Python3




#Python code for the above approach:
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
def closest_tribonacci(num):
    # Compute the closest Tribonacci number to the given num
    tribonacci = [0, 1, 1]
    while tribonacci[-1] < num:
        next_trib = tribonacci[-1] + tribonacci[-2] + tribonacci[-3]
        tribonacci.append(next_trib)
    min_diff = abs(num - tribonacci[0])
    closest_trib = tribonacci[0]
    for i in range(1, len(tribonacci)):
        diff = abs(num - tribonacci[i])
        if diff < min_diff:
            min_diff = diff
            closest_trib = tribonacci[i]
    return closest_trib
 
def replaceWithClosestTribonacci(head):
    # Replace the values in the linked list with the closest Tribonacci numbers
    curr = head
    while curr:
        closest_trib = closest_tribonacci(curr.val)
        curr.val = closest_trib
        curr = curr.next
    return head
 
def printList(head):
    # Print the linked list
    curr = head
    while curr:
        print(curr.val, "->", end=" ")
        curr = curr.next
    print("null")
 
# Driver code
if __name__ == "__main__":
    head = Node(2)
    head.next = Node(8)
    head.next.next = Node(14)
    head.next.next.next = Node(5)
    head.next.next.next.next = Node(16)
 
    # Function call to replace values with closest Tribonacci numbers
    replaceWithClosestTribonacci(head)
 
    # Print the modified linked list
    printList(head)


C#




// C# code for the above approach:
using System;
using System.Collections.Generic;
 
// Define the linked list node
class Node
{
    public int val;
    public Node next;
 
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
class Program
{
    // Helper function to compute the closest Tribonacci number
    static int ClosestTribonacci(int num)
    {
        List<int> tribonacci = new List<int>() { 0, 1, 1 };
        while (tribonacci[tribonacci.Count - 1] < num)
        {
            int nextTrib = tribonacci[tribonacci.Count - 1] +
                           tribonacci[tribonacci.Count - 2] +
                           tribonacci[tribonacci.Count - 3];
            tribonacci.Add(nextTrib);
        }
        int minDiff = Math.Abs(num - tribonacci[0]);
        int closestTrib = tribonacci[0];
        for (int i = 1; i < tribonacci.Count; i++)
        {
            int diff = Math.Abs(num - tribonacci[i]);
            if (diff < minDiff)
            {
                minDiff = diff;
                closestTrib = tribonacci[i];
            }
        }
        return closestTrib;
    }
 
    // Function to replace linked list nodes with closest
   // Tribonacci numbers
    static Node ReplaceWithClosestTribonacci(Node head)
    {
        Node curr = head;
        while (curr != null)
        {
            int closestTrib = ClosestTribonacci(curr.val);
            curr.val = closestTrib;
            curr = curr.next;
        }
        return head;
    }
 
    // Function to print list
    static void PrintList(Node head)
    {
        Node curr = head;
        while (curr != null)
        {
            Console.Write(curr.val + "->");
            curr = curr.next;
        }
        Console.WriteLine("null");
    }
 
    // Driver code
    static void Main()
    {
        Node head = new Node(2);
        head.next = new Node(8);
        head.next.next = new Node(14);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(16);
 
        // Function call
        ReplaceWithClosestTribonacci(head);
 
        PrintList(head);
    }
}


Javascript




class Node {
    constructor(x) {
        this.val = x;
        this.next = null;
    }
}
 
function closestTribonacci(num) {
    const tribonacci = [0, 1, 1];
 
    while (tribonacci[tribonacci.length - 1] < num) {
        const nextTrib = tribonacci[tribonacci.length - 1]
                        + tribonacci[tribonacci.length - 2]
                        + tribonacci[tribonacci.length - 3];
        tribonacci.push(nextTrib);
    }
 
    let minDiff = Math.abs(num - tribonacci[0]);
    let closestTrib = tribonacci[0];
 
    for (let i = 1; i < tribonacci.length; i++) {
        const diff = Math.abs(num - tribonacci[i]);
        if (diff < minDiff) {
            minDiff = diff;
            closestTrib = tribonacci[i];
        }
    }
 
    return closestTrib;
}
 
function replaceWithClosestTribonacci(head) {
    let curr = head;
 
    while (curr !== null) {
        const closestTrib = closestTribonacci(curr.val);
        curr.val = closestTrib;
        curr = curr.next;
    }
 
    return head;
}
 
function printList(head) {
    let curr = head;
    while (curr !== null) {
        process.stdout.write(curr.val + "->");
        curr = curr.next;
    }
    console.log("null");
}
 
// Driver code
const head = new Node(2);
head.next = new Node(8);
head.next.next = new Node(14);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(16);
 
// Function call to replace values with closest Tribonacci numbers
replaceWithClosestTribonacci(head);
 
// Print the modified linked list
printList(head);


Output

2->7->13->4->13->null













Time Complexity: O(n * log(num))
Auxiliary Space: O(1)

Approach 2:

Approach: This can be solved with the following idea:

In this approach, we generate the Tribonacci numbers separately and then find the closest Tribonacci number for each node’s value.

Here’s the step-by-step approach:

  • Create a helper function generateTribonacciNumbers(limit) that generates the Tribonacci numbers up to the given limit and returns them as a vector.
  • Traverse the linked list and store the values in a vector values.
  • Find the maximum value max_val in the values vector.
  • Generate the Tribonacci numbers up to max_val using the helper function.
  • Traverse the linked list again and replace each node’s value with its closest Tribonacci number.
    • For each node’s value val, iterate through the Tribonacci numbers and find the closest number to val.
    • Update the node’s value with the closest Tribonacci number.
  • Return the head of the modified linked list.

Below is the implementation of the above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
// Define the linked list node
struct Node {
    int val;
    Node* next;
    Node(int x)
        : val(x)
        , next(nullptr)
    {
    }
};
 
// Helper function to generate Tribonacci numbers
vector<int> generateTribonacciNumbers(int limit)
{
    vector<int> tribonacci = { 0, 1, 1 };
    int i = 3;
    while (tribonacci[i - 1] <= limit) {
        tribonacci.push_back(tribonacci[i - 1]
                             + tribonacci[i - 2]
                             + tribonacci[i - 3]);
        i++;
    }
    return tribonacci;
}
 
// Function to replace linked list nodes with closest
// Tribonacci numbers
Node* replaceWithClosestTribonacci(Node* head)
{
    // Store the values in a vector
    vector<int> values;
    Node* curr = head;
    while (curr != nullptr) {
        values.push_back(curr->val);
        curr = curr->next;
    }
 
    // Find the maximum value in the vector
    int max_val
        = *max_element(values.begin(), values.end());
 
    // Generate Tribonacci numbers up to max_val
    vector<int> tribonacci
        = generateTribonacciNumbers(max_val);
 
    // Replace node values with closest Tribonacci numbers
    curr = head;
    int n = tribonacci.size();
    for (int val : values) {
        int diff = INT_MAX;
        int closest_trib = 0;
        for (int i = 0; i < n; i++) {
            if (abs(val - tribonacci[i]) < diff) {
                diff = abs(val - tribonacci[i]);
                closest_trib = tribonacci[i];
            }
        }
        curr->val = closest_trib;
        curr = curr->next;
    }
 
    return head;
}
 
// Function to print list
void printList(Node* head)
{
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->val << "->";
        curr = curr->next;
    }
    cout << "null" << endl;
}
 
// Driver code
int main()
{
    Node* head = new Node(2);
    head->next = new Node(8);
    head->next->next = new Node(14);
    head->next->next->next = new Node(5);
    head->next->next->next->next = new Node(16);
 
    // Function call
    replaceWithClosestTribonacci(head);
 
    printList(head);
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
// Define the linked list node
class Node {
    int val;
    Node next;
 
    public Node(int x) {
        val = x;
        next = null;
    }
}
 
public class Main {
    // Helper function to generate Tribonacci numbers
    public static List<Integer> generateTribonacciNumbers(int limit) {
        List<Integer> tribonacci = new ArrayList<>();
        tribonacci.add(0);
        tribonacci.add(1);
        tribonacci.add(1);
 
        int i = 3;
        while (tribonacci.get(i - 1) <= limit) {
            tribonacci.add(tribonacci.get(i - 1) + tribonacci.get(i - 2) + tribonacci.get(i - 3));
            i++;
        }
 
        return tribonacci;
    }
 
    // Function to replace linked list nodes with closest Tribonacci numbers
    public static Node replaceWithClosestTribonacci(Node head) {
        // Store the values in a list
        List<Integer> values = new ArrayList<>();
        Node curr = head;
        while (curr != null) {
            values.add(curr.val);
            curr = curr.next;
        }
 
        // Find the maximum value in the list
        int maxVal = values.stream().mapToInt(Integer::intValue).max().orElse(0);
 
        // Generate Tribonacci numbers up to maxVal
        List<Integer> tribonacci = generateTribonacciNumbers(maxVal);
 
        // Replace node values with closest Tribonacci numbers
        curr = head;
        int n = tribonacci.size();
        for (int val : values) {
            int diff = Integer.MAX_VALUE;
            int closestTrib = 0;
            for (int i = 0; i < n; i++) {
                if (Math.abs(val - tribonacci.get(i)) < diff) {
                    diff = Math.abs(val - tribonacci.get(i));
                    closestTrib = tribonacci.get(i);
                }
            }
            curr.val = closestTrib;
            curr = curr.next;
        }
 
        return head;
    }
 
    // Function to print the list
    public static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.val + "->");
            curr = curr.next;
        }
        System.out.println("null");
    }
 
    // Driver code
    public static void main(String[] args) {
        Node head = new Node(2);
        head.next = new Node(8);
        head.next.next = new Node(14);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(16);
 
        // Function call
        replaceWithClosestTribonacci(head);
 
        printList(head);
    }
}


Python3




# Define the linked list node
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
# Helper function to generate Tribonacci numbers
def generateTribonacciNumbers(limit):
    tribonacci = [0, 1, 1]
    i = 3
    while tribonacci[i - 1] <= limit:
        tribonacci.append(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i - 3])
        i += 1
    return tribonacci
 
# Function to replace linked list nodes with closest
# Tribonacci numbers
def replaceWithClosestTribonacci(head):
      # Store the values
    values = []
    curr = head
    while curr != None:
        values.append(curr.val)
        curr = curr.next
    # Find the maximum value in the vector
    max_val = max(values)
     
    # Generate Tribonacci numbers up to max_val
    tribonacci = generateTribonacciNumbers(max_val)
     
    # Replace node values with closest Tribonacci numbers
    curr = head
    n = len(tribonacci)
    for val in values:
        diff = float('inf')
        closest_trib = 0
        for i in range(n):
            if abs(val - tribonacci[i]) < diff:
                diff = abs(val - tribonacci[i])
                closest_trib = tribonacci[i]
        curr.val = closest_trib
        curr = curr.next
    return head
 
# Function to print list
def printList(head):
    curr = head
    while curr != None:
        print(curr.val, "->", end="")
        curr = curr.next
    print("null")
 
# Driver code
head = Node(2)
head.next = Node(8)
head.next.next = Node(14)
head.next.next.next = Node(5)
head.next.next.next.next = Node(16)
replaceWithClosestTribonacci(head)
printList(head)


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
// Define the linked list node
public class Node
{
    public int val;
    public Node next;
     
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
class Program
{
    // Helper function to generate Tribonacci numbers
    public static List<int> GenerateTribonacciNumbers(int limit)
    {
        List<int> tribonacci = new List<int> { 0, 1, 1 };
        int i = 3;
        while (tribonacci[i - 1] <= limit)
        {
            tribonacci.Add(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i - 3]);
            i++;
        }
        return tribonacci;
    }
 
    // Function to replace linked list nodes with the closest Tribonacci numbers
    public static Node ReplaceWithClosestTribonacci(Node head)
    {
        // Store the values in a list
        List<int> values = new List<int>();
        Node curr = head;
        while (curr != null)
        {
            values.Add(curr.val);
            curr = curr.next;
        }
 
        // Find the maximum value in the list
        int max_val = values.Max();
 
        // Generate Tribonacci numbers up to max_val
        List<int> tribonacci = GenerateTribonacciNumbers(max_val);
 
        // Replace node values with the closest Tribonacci numbers
        curr = head;
        int n = tribonacci.Count;
        foreach (int val in values)
        {
            int diff = int.MaxValue;
            int closest_trib = 0;
            for (int i = 0; i < n; i++)
            {
                if (Math.Abs(val - tribonacci[i]) < diff)
                {
                    diff = Math.Abs(val - tribonacci[i]);
                    closest_trib = tribonacci[i];
                }
            }
            curr.val = closest_trib;
            curr = curr.next;
        }
 
        return head;
    }
 
    // Function to print the list
    public static void PrintList(Node head)
    {
        Node curr = head;
        while (curr != null)
        {
            Console.Write(curr.val + "->");
            curr = curr.next;
        }
        Console.WriteLine("null");
    }
 
    static void Main(string[] args)
    {
        Node head = new Node(2);
        head.next = new Node(8);
        head.next.next = new Node(14);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(16);
 
        // Function call
        ReplaceWithClosestTribonacci(head);
 
        PrintList(head);
    }
}


Javascript




<script>
// JavaScript code for the above approach
 
// Define the linked list node
class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}
 
// Helper function to generate Tribonacci numbers
function generateTribonacciNumbers(limit) {
    let tribonacci = [0, 1, 1];
    let i = 3;
    while (tribonacci[i - 1] <= limit) {
        tribonacci.push(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i - 3]);
        i++;
    }
    return tribonacci;
}
 
// Function to replace linked list nodes with closest Tribonacci numbers
function replaceWithClosestTribonacci(head) {
    // Store the values in an array
    let values = [];
    let curr = head;
    while (curr !== null) {
        values.push(curr.val);
        curr = curr.next;
    }
 
    // Find the maximum value in the array
    let max_val = Math.max(...values);
 
    // Generate Tribonacci numbers up to max_val
    let tribonacci = generateTribonacciNumbers(max_val);
 
    // Replace node values with closest Tribonacci numbers
    curr = head;
    let n = tribonacci.length;
    for (let val of values) {
        let diff = Number.MAX_SAFE_INTEGER;
        let closest_trib = 0;
        for (let i = 0; i < n; i++) {
            if (Math.abs(val - tribonacci[i]) < diff) {
                diff = Math.abs(val - tribonacci[i]);
                closest_trib = tribonacci[i];
            }
        }
        curr.val = closest_trib;
        curr = curr.next;
    }
 
    return head;
}
 
// Function to print list
function printList(head) {
    let curr = head;
    while (curr !== null) {
        document.write(curr.val + "->");
        curr = curr.next;
    }
    document.write("null");
}
 
// Driver code
let head = new Node(2);
head.next = new Node(8);
head.next.next = new Node(14);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(16);
 
// Function call
replaceWithClosestTribonacci(head);
 
printList(head);
 
// This code is contributed by Susobhan Akhuli
</script>


Output

2->7->13->4->13->null













Time Complexity:  O(limit + n)
Auxiliary Space:  O(limit + n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads