![]() |
VOOZH | about |
Given a singly linked list, the task is to replace every node with its closest triangular number.
Examples:
Input: 3 -> 9 -> 21 -> 25 -> NULL
Output: 3 -> 10 -> 21 -> 28 -> NULL
Explanation: The closest Triangular numbers for each node are:
- Node 1 (value = 3): Closest Triangular number = 3.
- Node 2 (value = 9): Closest Triangular number = 10.
- Node 3 (value = 21): Closest Triangular number = 21.
- Node 4 (value = 25): Closest Triangular number = 28.
Input: 10 -> 15 -> 30 -> 40 -> 50 -> NULL
Output: 10 -> 15 -> 28-> 36 -> 45 -> NULL
Explanation: The closest Triangular numbers for each node are:
- Node 1 (value = 10): Closest Triangular number = 10.
- Node 2 (value = 15): Closest Triangular number = 15.
- Node 3 (value = 30): Closest Triangular number = 28.
- Node 4 (value = 40): Closest Triangular number = 36.
- Node 5 (value = 50): Closest Triangular number = 45.
Approach: This can be solved with the following idea:
This approach uses the concept of triangular numbers to replace every node in a linked list with its closest triangular number. Triangular numbers are the numbers that can be represented in the form of a triangular grid of points, where each row contains one more point than the previous one. The nth triangular number is the sum of the first n natural numbers, i.e., T(n) = 1 + 2 + ... + n = n(n+1)/2. To find the closest triangular number for a given integer, we first find the smallest triangular number that is greater than or equal to the given integer. We can use the formula for the nth triangular number to find this. If the difference between this triangular number and the given integer is less than the difference between the previous triangular number and the given integer, we choose this triangular number as the closest one. Otherwise, we choose the previous triangular number as the closest one. Using this approach, we iterate through the linked list and replace the value of each node with its closest triangular number. Finally, we return the head of the modified linked list and print it to verify the output.
Steps of the above approach:
Below is the implementation of the above approach:
3 -> 10 -> 21 -> 28 -> NULL
Time Complexity: O(n + sqrt(n))
Auxiliary Space: O(1), since we are not using any extra space.