#2058
Find the Minimum and Maximum Number of Nodes Between Critical Points
MediumLinked ListTwo PointersSliding WindowArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach efficiently finds critical points in a single pass and calculates distances in another pass. It reduces unnecessary comparisons and leverages the structure of the linked list.
⚙️
Algorithm
3 steps- 1Step 1: Traverse the linked list to identify all critical points and store their indices.
- 2Step 2: Calculate minDistance by checking the difference between consecutive critical points.
- 3Step 3: The maxDistance is simply the difference between the first and last critical points.
solution.py26 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def nodesBetweenCriticalPoints(head):
8 critical_points = []
9 current = head
10 index = 0
11 while current and current.next and current.next.next:
12 if (current.val < current.next.val > current.next.next.val) or (current.val > current.next.val < current.next.next.val):
13 critical_points.append(index + 1)
14 current = current.next
15 index += 1
16
17 if len(critical_points) < 2:
18 return [-1, -1]
19
20 min_distance = float('inf')
21 max_distance = critical_points[-1] - critical_points[0]
22
23 for i in range(len(critical_points) - 1):
24 min_distance = min(min_distance, critical_points[i + 1] - critical_points[i])
25
26 return [min_distance, max_distance]ℹ
Complexity note: The time complexity is O(n) because we traverse the linked list once to find critical points and then calculate distances in a single pass. The space complexity is O(n) due to storing the indices of critical points.
- 1Critical points can only be identified if there are at least three nodes in the list.
- 2The maximum distance is always between the first and last critical point.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.