Find the Minimum and Maximum Number of Nodes Between Critical Points - Problem

A critical point in a linked list is defined as either a local maxima or a local minima.

A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.

A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.

Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.

Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].

Input & Output

Example 1 — Basic Case with Multiple Critical Points
$ Input: head = [3,1]
Output: [-1,-1]
💡 Note: There are no critical points in [3,1] since we need at least 3 nodes to have a node with both previous and next nodes.
Example 2 — Sufficient Critical Points
$ Input: head = [5,3,1,2,5,1,2]
Output: [1,3]
💡 Note: Critical points are at indices 1 (local maxima: 3>5 and 3>1), 2 (local minima: 1<3 and 1<2), and 5 (local minima: 1<5 and 1<2). Min distance is 1 (between indices 1 and 2), max distance is 4 (between indices 1 and 5).
Example 3 — Only Two Critical Points
$ Input: head = [1,3,2,2,3,2,2,2,7]
Output: [3,3]
💡 Note: Critical points are at indices 1 (local maxima: 3>1 and 3>2) and 4 (local maxima: 3>2 and 3>2). Distance between them is 3, so both min and max distances are 3.

Constraints

  • The number of nodes in the list is in the range [2, 105]
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
Critical Points: Local Maxima and Minima in Linked List531251201 (max)2 (min)345 (min)6Critical Points at positions: 1 (local max), 2 (local min), 5 (local min)Distances: 1→2 = 1, 1→5 = 4, 2→5 = 3Minimum Distance: 1, Maximum Distance: 4Result: [1, 4]
Understanding the Visualization
1
Input
Linked list with values: [5,3,1,2,5,1,2]
2
Find Critical Points
Identify positions where value is local max/min compared to neighbors
3
Calculate Distances
Find minimum and maximum distances between critical points
Key Takeaway
🎯 Key Insight: Track first and previous critical point positions to calculate min/max distances in one pass
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen