2058. Find the Minimum and Maximum Number of Nodes Between Critical Points
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Find the Minimum and Maximum Number of Nodes Between Critical Points (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Linked List pattern in coding interviews. Single pass tracking first and last critical point indices; compute min gap between consecutive.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Single pass tracking first and last critical point indices; compute min gap between consecutive.
Related patterns: Array, Linked List, Two Pointers
2058.cs
C#
// Approach: Single pass tracking first and last critical point indices; compute min gap between consecutive.
// Time: O(n) Space: O(1)
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 minDistance = Int32.MaxValue;
int firstMaIndex = -1, prevMaIndex = -1, index = 1;
ListNode prev = head;
ListNode curr = head.next;
while (curr.next != null)
{
if (curr.val > prev.val && curr.val > curr.next.val ||
curr.val < prev.val && curr.val < curr.next.val)
{
if (firstMaIndex == -1)
firstMaIndex = index;
if (prevMaIndex != -1)
minDistance = Math.Min(minDistance, index - prevMaIndex);
prevMaIndex = index;
}
prev = curr;
curr = curr.next;
index++;
}
if (minDistance == Int32.MaxValue)
return new int[] { -1, -1 };
return new int[] { minDistance, prevMaIndex - firstMaIndex };
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 19. Remove Nth Node From End of List(Medium)
- 25. Reverse Nodes in k-Group(Hard)