Find the Minimum and Maximum Number of Nodes Between Critical Points (LeetCode 2058): Solution and Explanation

Medium
Linked List

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

  1. Set first = last = -1 and min_dist = infinity.
  2. Start with prev = head, curr = head.next and index i = 1.
  3. While curr.next exists, check whether curr.val is strictly greater than both neighbors or strictly smaller than both.
  4. If it is critical and first == -1, set first = i. Otherwise update min_dist = min(min_dist, i - last).
  5. Set last = i for every critical node, then slide the window forward one node.
  6. If first == last, return [-1, -1]. Otherwise return [min_dist, last - first].

Step-by-step example

head = [5,3,1,2,5,1,2]
  1. Index 1 (3): 5 > 3 > 1, a slope, not critical.
  2. Index 2 (1): below 3 and 2, a local min. first = last = 2.
  3. Index 3 (2): 1 < 2 < 5, not critical.
  4. Index 4 (5): above 2 and 1, a local max. Gap 4 - 2 = 2, so min_dist = 2. last = 4.
  5. Index 5 (1): below 5 and 2, a local min. Gap 1, so min_dist = 1. last = 5.
  6. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is visited once as the middle of the window, and each check is constant work.

Space

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.