Given a linked list, the task is to find the sum of distances between the two nearest perfect squares for all the nodes of the given linked list.
Input: 3 -> 15 -> 7 -> NULL
For 3: closest left perfect square is 1 and closest right 4 i.e. 4-1 = 3
For 15: 16 – 9 = 7
For 7: 9 – 4 = 5
3 + 7 + 5 = 15
Input: 1 -> 5 -> 10 -> 78 -> 23 -> NULL
Approach: Initialise sum = 0 and for every node, if the current node’s value is a perfect square itself then the left and right closest perfect square will be the value itself and distance will be 0. Else, find the left and right closest perfect squares say leftPS and rightPS and update sum = sum + (rightPS – leftPS).
Below is the implementation of the above approach:
Time Complexity: O(n)
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Delete N nodes after M nodes of a linked list
- Linked List Sum of Nodes Between 0s
- Sum of the nodes of a Singly Linked List
- Sum and Product of all the nodes which are less than K in the linked list
- Sum of the alternate nodes of linked list
- Linked List Product of Nodes Between 0s
- Find the sum of last n nodes of the given Linked List
- Sum of the nodes of a Circular Linked List
- Sum of all distinct nodes in a linked list
- Find sum of even and odd nodes in a linked list
- Segregate even and odd nodes in a Linked List
- Sum of all odd frequency nodes of the Linked List
- Exchange first and last nodes in Circular Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.