Skip to content

Commit ac7c406

Browse files
Add detailed explanation of code
1 parent c0bf515 commit ac7c406

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Intuition
2+
The task is to find critical points in a linked list and calculate the minimum and maximum distances between these points. Critical points are nodes that are either local maxima or local minima. A node is a local maxima if its value is greater than both its previous and next nodes. Similarly, a node is a local minima if its value is less than both its previous and next nodes.
3+
4+
Approach
5+
Identify Critical Points: Traverse the linked list and identify nodes that are either local maxima or local minima by comparing each node's value with its previous and next nodes. Store the indices of these critical points.
6+
Calculate Distances:
7+
If there are fewer than two critical points, return [-1, -1].
8+
Otherwise, calculate the minimum distance between any two consecutive critical points and the maximum distance between the first and last critical points in the list.
9+
Complexity
10+
Time complexity:O(n)
11+
Space complexity:O(1)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <vector>
2+
#include <iostream>
3+
#include <climits>
4+
using namespace std;
5+
6+
struct ListNode
7+
{
8+
int val;
9+
ListNode *next;
10+
ListNode() : val(0), next(nullptr) {}
11+
ListNode(int x) : val(x), next(nullptr) {}
12+
ListNode(int x, ListNode *next) : val(x), next(next) {}
13+
};
14+
15+
class Solution
16+
{
17+
public:
18+
vector<int> nodesBetweenCriticalPoints(ListNode *head)
19+
{
20+
vector<int> store;
21+
22+
int ans1 = INT_MAX, cur, next, n;
23+
int last = head->val, position = 2;
24+
25+
while (head->next)
26+
{
27+
cur = head->val, next = head->next->val;
28+
29+
if ((last > cur and cur < next) or (last < cur and cur > next))
30+
store.push_back(position);
31+
position++;
32+
last = cur, head = head->next;
33+
34+
n = store.size();
35+
if (n > 1)
36+
ans1 = min(ans1, store[n - 1] - store[n - 2]);
37+
}
38+
39+
if (ans1 == INT_MAX)
40+
return {-1, -1};
41+
42+
return {ans1, store.back() - store[0]};
43+
}
44+
};

0 commit comments

Comments
 (0)