29. Delete nodes having greater value on right
The problem can be found at the following link: Question Link
My Approach
I applied a recursive backtracking approach to solve the problem, following these steps:
Initiate the traversal of all nodes through recursion, and subsequently retrace the path, starting from the last node and moving in a right-to-left direction.
Keep track of the maximum node encountered so far.
If the current node's data is less than the maximum, delete the current node.
Otherwise, update the maximum node.
Continue this process for all nodes.
Explanation with example
Consider the following example:
Time and Auxiliary Space Complexity
Time Complexity:
O(N)
, whereN
is the number of nodes in the linked list. We visit each node once.Auxiliary Space Complexity:
O(N)
due to the recursive function call stack.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated