Problem Description
Given a linked list, a critical point is defined as either a local maxima or a local minima. A node is considered a local maximum if its value is strictly greater than both its previous and next node's values, while it is a local minimum if its value is strictly smaller than both. Note that the first and last nodes are not eligible as they do not have both neighbors. The task is to determine the minimum and maximum distances (in terms of node positions) between any two critical points in the list. If there are fewer than two critical points, return [-1, -1].
Key Insights
- Traverse the list while comparing each node (except the first and last) with its previous and next nodes.
- Record the index positions (starting from 1) of all critical points.
- The minimum distance is found by evaluating consecutive positions, while the maximum distance is the gap between the first and the last critical nodes.
- If less than two critical points are found, return [-1, -1].
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the linked list. Space Complexity: O(n) in the worst case for storing indices of critical points.
Solution
The solution involves a single traversal of the linked list. As you iterate from the second node to the second-last node, compare the current node's value with its neighbors to determine if it's a critical point and record its index. After identifying all critical positions, the minimum distance is the smallest difference between consecutive critical indices, and the maximum distance is the difference between the first and last recorded indices. A few edge cases include lists with fewer than two critical points.