Find the Minimum and Maximum Number of Nodes Between Critical Points solution and explanation
9 more videos on this problem
Find the Minimum and Maximum Number of Nodes Between Critical Points | 2 Ways | Leetcode 2058codestorywithMIK · 31:41 · 7K views
Find the Minimum and Maximum Number of Nodes Between Critical Points - Leetcode 2058 - PythonNeetCodeIO · 12:10 · 7K views
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points | Greedy | Linked ListAryan Mittal · 18:07 · 2K views
Leetcode 2058. Find the Minimum and Maximum Number of Nodes Between Critical PointsElite Code · 30:27 · 499 views
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points (Leetcode Medium)Programming Live with Larry · 6:48 · 414 views
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points | Leetcode Daily 5/7/2024AlgorithmHQ · 15:17 · 347 views
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points || Leetcode || HindiCoding Sphere · 11:27 · 227 views
LeetCode 2058 - Find the Minimum And Maximum Number of Nodes Between Critical Points - JavaAlpha-Code · 11:35 · 63 views
Leetcode 2058. Find the Minimum and Maximum Number of Nodes Between Critical PointsQuasar · 1:59 · 21 views
Find the Minimum and Maximum Number of Nodes Between Critical Points #2058 #leetcode #pythonchillX · 10:44 · 19 views
The 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].
Example 1:
Input: head = [3,1] Output: [-1,-1] Explanation: There are no critical points in [3,1].
Example 2:
Input: head = [5,3,1,2,5,1,2] Output: [1,3] Explanation: There are three critical points: - [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. - [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. - [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.
Example 3:
Input: head = [1,3,2,2,3,2,2,2,7] Output: [3,3] Explanation: There are two critical points: - [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. - [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. Both the minimum and maximum distances are between the second and the fifth node. Thus, minDistance and maxDistance is 5 - 2 = 3. Note that the last node is not considered a local maxima because it does not have a next node.
Constraints:
- The number of nodes in the list is in the range
[2, 105]. 1 <= Node.val <= 105
Approach overview
Problem Overview: You are given a linked list and must identify all critical points. A node is critical if it is strictly greater than both neighbors (local maxima) or strictly smaller than both neighbors (local minima). After locating all such nodes, compute the minimum and maximum distance between any two critical points based on their positions in the list.
Approach 1: Single Pass and Collect Critical Points (O(n) time, O(1) space)
Traverse the linked list once while keeping track of the previous, current, and next node values. When the current value forms a local maximum or minimum, record its index as a critical point. Maintain the first critical index, the previous critical index, and update the minimum distance using the gap between consecutive critical points. The maximum distance is simply the difference between the first and the latest critical point. This works because the list is processed sequentially, so consecutive critical points are discovered in order.
This approach uses constant extra space since you only store a few index variables instead of all positions. It is the most efficient implementation and fits well with typical linked list traversal patterns.
Approach 2: Two-pass Approach for Clarity (O(n) time, O(k) space)
First iterate through the list and store the indices of all critical points in an array. After the traversal, compute the minimum distance by scanning adjacent elements in the array. The maximum distance is simply the difference between the first and last stored indices. Although this approach uses extra memory proportional to the number of critical points, it separates detection from distance calculation, which can make the logic easier to reason about.
This version is helpful when debugging or when you prefer clearer separation between scanning and computation steps. The algorithm still runs in linear time since each node is visited once.
Recommended for interviews: The single-pass solution is what most interviewers expect. It demonstrates strong understanding of linked list traversal and efficient state tracking. Implementing the two-pass version first can help verify the logic, but optimizing to a single traversal shows stronger algorithmic thinking.
Approach 1: Single Pass and Collect Critical Points
In this approach, we traverse the linked list in a single pass, collecting the positions of critical points (local minima and maxima) along the way. We maintain two variables, `firstCritical` and `lastCritical`, to track the position of the first and the last critical points encountered. Additionally, we calculate the minimum distance between consecutive critical points using a running minimum distance variable.
Finally, the maximum distance is the distance between the first and last critical points if at least two critical points are found. Otherwise, return [-1, -1] if fewer than two critical points exist.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def nodesBetweenCriticalPoints(self, head: ListNode) -> List[int]:
index = 1
prev = head
curr = head.next
first_critical = last_critical = -1
min_dist = float('inf')
while curr and curr.next:
if (curr.val > prev.val and curr.val > curr.next.val) or (curr.val < prev.val and curr.val < curr.next.val):
if first_critical == -1:
first_critical = index
else:
min_dist = min(min_dist, index - last_critical)
last_critical = index
prev = curr
curr = curr.next
index += 1
if first_critical == -1:
return [-1, -1]
return [min_dist, last_critical - first_critical]class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; next = null; }
}
public class Solution {
public int[] nodesBetweenCriticalPoints(ListNode head) {
int firstCritical = -1, lastCritical = -1, minDist = Integer.MAX_VALUE;
int index = 1;
ListNode prev = head;
ListNode curr = head.next;
while (curr != null && curr.next != null) {
if ((curr.val > prev.val && curr.val > curr.next.val) ||
(curr.val < prev.val && curr.val < curr.next.val)) {
if (firstCritical == -1) {
firstCritical = index;
} else {
minDist = Math.min(minDist, index - lastCritical);
}
lastCritical = index;
}
prev = curr;
curr = curr.next;
index++;
}
if (firstCritical == -1) return new int[]{-1, -1};
return new int[]{minDist, lastCritical - firstCritical};
}
}#include <vector>
#include <climits>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
vector<int> nodesBetweenCriticalPoints(ListNode* head) {
int firstCritical = -1, lastCritical = -1, minDist = INT_MAX, index = 1;
ListNode* prev = head;
ListNode* curr = head->next;
while (curr && curr->next) {
if ((curr->val > prev->val && curr->val > curr->next->val) ||
(curr->val < prev->val && curr->val < curr->next->val)) {
if (firstCritical == -1) {
firstCritical = index;
} else {
minDist = min(minDist, index - lastCritical);
}
lastCritical = index;
}
prev = curr;
curr = curr->next;
index++;
}
if (firstCritical == -1) return {-1, -1};
return {minDist, lastCritical - firstCritical};
}
};function ListNode(val, next = null) {
this.val = val;
this.next = next;
}
var nodesBetweenCriticalPoints = function(head) {
let index = 1;
let prev = head;
let curr = head.next;
let firstCritical = -1, lastCritical = -1;
let minDist = Infinity;
while (curr !== null && curr.next !== null) {
if ((curr.val > prev.val && curr.val > curr.next.val) ||
(curr.val < prev.val && curr.val < curr.next.val)) {
if (firstCritical === -1) {
firstCritical = index;
} else {
minDist = Math.min(minDist, index - lastCritical);
}
lastCritical = index;
}
prev = curr;
curr = curr.next;
index++;
}
if (firstCritical === -1) return [-1, -1];
return [minDist, lastCritical - firstCritical];
};#include <stdlib.h>
#include <limits.h>
struct ListNode {
int val;
struct ListNode* next;
};
int* nodesBetweenCriticalPoints(struct ListNode* head, int* returnSize) {
*returnSize = 2;
int* result = (int*)malloc(2 * sizeof(int));
int firstCritical = -1, lastCritical = -1, minDist = INT_MAX;
int index = 1;
struct ListNode* prev = head;
struct ListNode* curr = head->next;
while (curr && curr->next) {
if ((curr->val > prev->val && curr->val > curr->next->val) ||
(curr->val < prev->val && curr->val < curr->next->val)) {
if (firstCritical == -1) {
firstCritical = index;
} else {
minDist = min(minDist, index - lastCritical);
}
lastCritical = index;
}
prev = curr;
curr = curr->next;
index++;
}
if (firstCritical == -1) {
result[0] = -1;
result[1] = -1;
} else {
result[0] = minDist;
result[1] = lastCritical - firstCritical;
}
return result;
}public class ListNode {
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null) {
this.val = val;
this.next = next;
}
}
public class Solution {
public int[] NodesBetweenCriticalPoints(ListNode head) {
int firstCritical = -1, lastCritical = -1, minDist = int.MaxValue, index = 1;
ListNode prev = head;
ListNode curr = head.next;
while (curr != null && curr.next != null) {
if ((curr.val > prev.val && curr.val > curr.next.val) ||
(curr.val < prev.val && curr.val < curr.next.val)) {
if (firstCritical == -1) {
firstCritical = index;
} else {
minDist = System.Math.Min(minDist, index - lastCritical);
}
lastCritical = index;
}
prev = curr;
curr = curr.next;
index++;
}
if (firstCritical == -1) return new int[]{-1, -1};
return new int[]{minDist, lastCritical - firstCritical};
}
}We iterate over the linked list using a while loop, checking if the current node is a local maxima or minima by comparing it with its previous and next nodes. We track the indices of the first and last critical points discovered. Whenever another critical point is found, we update the minimum distance using the index difference from the last critical point.
If fewer than two critical points are found, we return [-1, -1]; otherwise, the result is an array of [minDistance, maxDistance].
The time complexity of this solution is O(n), where n is the number of nodes in the linked list, because we traverse the list only once. The space complexity is O(1), since we only use a static amount of additional space.
Approach 2: Two-pass Approach for Clarity
This approach resolves the problem using two full passes over the linked list for clearer data separation. In the first traversal, we gather all the indices of critical points into a list. During the second traversal over the list of critical points, we calculate the minimum and maximum distances between critical point pairs.
This method enhances clarity by separately collecting and then processing data, although it might sacrifice some execution time compared to a single-pass solution.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def nodesBetweenCriticalPoints(self, head: ListNode) -> List[int]:
indices = []
index = 1
prev = head
curr = head.next
while curr and curr.next:
if (curr.val > prev.val and curr.val > curr.next.val) or (curr.val < prev.val and curr.val < curr.next.val):
indices.append(index)
prev = curr
curr = curr.next
index += 1
if len(indices) < 2:
return [-1, -1]
min_dist = float('inf')
for i in range(1, len(indices)):
min_dist = min(min_dist, indices[i] - indices[i - 1])
max_dist = indices[-1] - indices[0]
return [min_dist, max_dist]This Python version uses two loops over a linked list. The first loop extracts indices of critical points, and the second loop computes the desired statistics from them, aiding in understandability and ensuring comprehensive error handling.
The time complexity is O(n) as it traverses the list twice, but the proportional dependence on n remains. Space complexity is O(k), where k is the number of critical points stored.
Approach 3: Direct Traversal
Based on the problem description, we need to find the positions of the first and last critical points in the linked list, first and last, respectively. This allows us to calculate the maximum distance maxDistance = last - first. For the minimum distance minDistance, we need to traverse the linked list, calculate the distance between two adjacent critical points, and take the minimum value.
The time complexity is O(n), where n is the length of the linked list. The space complexity is O(1).
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function nodesBetweenCriticalPoints(head: ListNode | null): number[] {
const ans: number[] = [Infinity, 0];
let [first, last] = [-1, -1];
for (let i = 0; head.next.next; head = head.next, ++i) {
const [a, b, c] = [head.val, head.next.val, head.next.next.val];
if (b < Math.min(a, c) || b > Math.max(a, c)) {
if (last < 0) {
first = i;
last = i;
} else {
ans[0] = Math.min(ans[0], i - last);
last = i;
ans[1] = Math.max(ans[1], last - first);
}
}
}
return first === last ? [-1, -1] : ans;
}/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func nodesBetweenCriticalPoints(head *ListNode) []int {
ans := []int{1 << 30, 0}
first, last := -1, -1
for i := 0; head.Next.Next != nil; head, i = head.Next, i+1 {
a, b, c := head.Val, head.Next.Val, head.Next.Next.Val
if b < min(a, c) || b > max(a, c) {
if last == -1 {
first, last = i, i
} else {
ans[0] = min(ans[0], i-last)
last = i
ans[1] = max(ans[1], last-first)
}
}
}
if first == last {
return []int{-1, -1}
}
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Single Pass and Collect Critical Points | The time complexity of this solution is O(n), where n is the number of nodes in the linked list, because we traverse the list only once. The space complexity is O(1), since we only use a static amount of additional space. |
| Two-pass Approach for Clarity | The time complexity is O(n) as it traverses the list twice, but the proportional dependence on n remains. Space complexity is O(k), where k is the number of critical points stored. |
| Direct Traversal | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Single Pass and Track Critical Indices | O(n) | O(1) | Best for interviews and production when you want optimal memory usage |
| Two-pass with Stored Critical Points | O(n) | O(k) | Useful for clarity or debugging when storing all critical indices simplifies logic |
Frequently asked questions
Is Find the Minimum and Maximum Number of Nodes Between Critical Points easy or hard?
The problem is rated Medium because it combines linked list traversal with careful index tracking. Detecting local minima and maxima is straightforward, but correctly maintaining distances between critical points requires attention to edge cases such as having fewer than two critical points.
Find the Minimum and Maximum Number of Nodes Between Critical Points Python/Java solution
Both Python and Java implementations follow the same logic: traverse the linked list while tracking indices and detecting local minima or maxima. Maintain variables for the first critical index, previous critical index, and minimum distance. Update distances whenever a new critical point is found. The overall complexity remains O(n) time and O(1) extra space.
How to solve Find the Minimum and Maximum Number of Nodes Between Critical Points in O(n)?
Traverse the linked list while keeping track of three nodes: previous, current, and next. When the current value is strictly greater than both neighbors or strictly smaller than both, mark its index as a critical point. Update the minimum distance using the difference from the previous critical point, and update the maximum distance using the difference from the first critical point. Continue until the list ends.
What is the best approach for Find the Minimum and Maximum Number of Nodes Between Critical Points?
The best approach is a single-pass traversal of the linked list while tracking critical points. During iteration, check if the current node forms a local minimum or maximum compared with its neighbors. Track the first and previous critical indices to compute minimum and maximum distances on the fly. This solution runs in O(n) time and O(1) space.
Is Find the Minimum and Maximum Number of Nodes Between Critical Points asked at Google/Amazon/Meta?
Linked list traversal and local extrema detection problems appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may not always appear, the pattern of scanning a linked list and tracking positions of special nodes is a common interview topic.
What data structure is used in Find the Minimum and Maximum Number of Nodes Between Critical Points?
The core data structure is a singly linked list. The algorithm relies on sequential traversal and comparison of neighboring node values. Some implementations also use a small array or list to store indices of critical points, but the optimal approach keeps only a few index variables.
What is the time complexity of Find the Minimum and Maximum Number of Nodes Between Critical Points?
The optimal solution runs in O(n) time because each node in the linked list is visited exactly once during traversal. Distance calculations are constant-time updates when a new critical point is discovered. Space complexity can be O(1) if only indices are tracked, or O(k) if all critical point positions are stored.
