Find the Minimum and Maximum Number of Nodes Between Critical Points (LeetCode 2058): Solution and Explanation
A critical point is a node strictly above or strictly below both of its neighbors. Return the smallest and largest distance between two distinct critical points, or [-1, -1] if there are fewer than two.
Intuition
Whether a node is critical depends only on itself and its two neighbors. So a window of three nodes, prev, curr and next, slid one step at a time, classifies every interior node in a single pass. The head and tail never qualify because they are missing a neighbor.
You do not need to store every critical index. The largest distance between any two critical points is the distance from the first one to the last one, since every other pair sits inside that span.
The smallest distance is always between two critical points that are next to each other in the order you find them. Any pair that skips over a critical point in the middle is at least as long as either half. So each time a new critical point appears, compare its index with the previous one and keep the minimum.
That leaves three numbers to track: first, last and min_dist. If first equals last at the end, there were zero or one critical points and the answer is [-1, -1].
Approach: One pass with a three-node window
- Set
first = last = -1andmin_dist = infinity. - Start with
prev = head,curr = head.nextand indexi = 1. - While
curr.nextexists, check whethercurr.valis strictly greater than both neighbors or strictly smaller than both. - If it is critical and
first == -1, setfirst = i. Otherwise updatemin_dist = min(min_dist, i - last). - Set
last = ifor every critical node, then slide the window forward one node. - If
first == last, return[-1, -1]. Otherwise return[min_dist, last - first].
Step-by-step example
head = [5,3,1,2,5,1,2]
- Index 1 (3): 5 > 3 > 1, a slope, not critical.
- Index 2 (1): below 3 and 2, a local min. first = last = 2.
- Index 3 (2): 1 < 2 < 5, not critical.
- Index 4 (5): above 2 and 1, a local max. Gap 4 - 2 = 2, so min_dist = 2. last = 4.
- Index 5 (1): below 5 and 2, a local min. Gap 1, so min_dist = 1. last = 5.
- Return [1, 5 - 2] = [1, 3].
Code: Python, Java, C++
1class Solution:
2 def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
3 first = last = -1
4 min_dist = float('inf')
5 prev, curr, i = head, head.next, 1
6 while curr.next:
7 if (prev.val < curr.val > curr.next.val) or (prev.val > curr.val < curr.next.val):
8 if first == -1:
9 first = i
10 else:
11 min_dist = min(min_dist, i - last)
12 last = i
13 prev, curr, i = curr, curr.next, i + 1
14 if first == last:
15 return [-1, -1]
16 return [min_dist, last - first]1class Solution {
2 public int[] nodesBetweenCriticalPoints(ListNode head) {
3 int first = -1, last = -1, minDist = Integer.MAX_VALUE;
4 ListNode prev = head, curr = head.next;
5 int i = 1;
6 while (curr.next != null) {
7 int a = prev.val, b = curr.val, c = curr.next.val;
8 if ((a < b && b > c) || (a > b && b < c)) {
9 if (first == -1) {
10 first = i;
11 } else {
12 minDist = Math.min(minDist, i - last);
13 }
14 last = i;
15 }
16 prev = curr;
17 curr = curr.next;
18 i++;
19 }
20 if (first == last) {
21 return new int[] {-1, -1};
22 }
23 return new int[] {minDist, last - first};
24 }
25}1class Solution {
2public:
3 vector<int> nodesBetweenCriticalPoints(ListNode* head) {
4 int first = -1, last = -1, minDist = INT_MAX;
5 ListNode* prev = head;
6 ListNode* curr = head->next;
7 int i = 1;
8 while (curr->next) {
9 int a = prev->val, b = curr->val, c = curr->next->val;
10 if ((a < b && b > c) || (a > b && b < c)) {
11 if (first == -1) {
12 first = i;
13 } else {
14 minDist = min(minDist, i - last);
15 }
16 last = i;
17 }
18 prev = curr;
19 curr = curr->next;
20 i++;
21 }
22 if (first == last) {
23 return {-1, -1};
24 }
25 return {minDist, last - first};
26 }
27};Time and space complexity
O(n)
Each node is visited once as the middle of the window, and each check is constant work.
O(1)
Only the three pointers and three integers are kept, no list of critical indices.
Other approaches
Collect critical indices, then scan (time O(n), space O(n))
Store every critical index in an array, then take the minimum gap between neighbors and the difference of the ends. It is easy to read but needs O(n) extra memory in the worst case.
Copy values into an array (time O(n), space O(n))
Convert the list to an array first so neighbors can be read by index. This avoids pointer handling but doubles the memory for no gain.
Common mistakes
- Using non-strict comparisons. A flat stretch like 2, 2, 3 does not make the middle 2 a local minimum.
- Counting the head or tail as critical. They have only one neighbor.
- Comparing every pair of critical points for the minimum, which is O(k^2). Consecutive pairs are enough.
- Returning
[inf, 0]when there is exactly one critical point instead of[-1, -1].
Frequently asked questions
Why is the maximum distance always last minus first?
Every critical point lies between the first and the last one, so no pair can be farther apart than those two.
Why only compare consecutive critical points for the minimum?
If a pair skips over another critical point, splitting it at that point gives two shorter gaps. The shortest gap overall must be between neighbors.
Are plateaus ever critical?
No. A critical node must be strictly greater or strictly smaller than both neighbors, so equal neighbors rule it out.
What is the time complexity of this problem?
O(n) time with a single pass, and O(1) extra space.