![]() |
VOOZH | about |
Given a singly linked list of integers, the task is to replace every node with its closest Fibonacci number and return the modified linked list.
Examples:
Input: List: 3->5->9->12->13->15->null
Output: 3->5->8->13->13->13->null
Explanation: The closest Fibonacci numbers for each node are:
- Node 1 (value = 3): Closest Fibonacci number = 3.
- Node 2 (value = 5): Closest Fibonacci number = 5.
- Node 3 (value = 9): Closest Fibonacci number = 8.
- Node 4 (value = 12): Closest Fibonacci number = 13.
- Node 5 (value = 13): Closest Fibonacci number = 13.
- Node 6 (value = 15): Closest Fibonacci number = 13.
Input: List : 1->2->3->4->5->null
Output: 1->2->3->5->5->null
Explanation: The closest Fibonacci numbers for each node are:
- Node 1 (value = 1): Closest Fibonacci number = 1.
- Node 2 (value = 2): Closest Fibonacci number = 2.
- Node 3 (value = 3): Closest Fibonacci number = 3.
- Node 4 (value = 4): Closest Fibonacci number = 5.
- Node 5 (value = 5): Closest Fibonacci number = 5.
Approach: This can be solved with the following idea:
This problem requires us to modify a linked list such that each node is replaced with its closest Fibonacci number. To solve this problem, we can start by creating an array of Fibonacci numbers that are greater than the maximum value in the linked list. We can then iterate over each node in the linked list, finding the closest Fibonacci number using the array we created.
Below are the steps for the above idea:
Below is the implementation of the above approach:
3->5->8->13->13->13->null
Time Complexity: O(n*logn)
Auxiliary Space: O(k)