Ctrl K

Gaps Between Turning Points

Medium
You get a singly linked list head. Call a node a turning point if it has both a previous and a next node and its value is strictly greater than both neighbours or strictly smaller than both. The first and last nodes are never turning points. The distance between two nodes is the difference of their positions in the list. Return [closest, farthest]: the smallest and the largest distance between two different turning points. If there are fewer than two turning points, return [-1, -1].
Example 1
head=list_node([4, 2, 6, 1, 3]) → [1, 2]

The turning nodes are 2 (below both neighbours), 6 (above) and 1 (below), at positions 1, 2 and 3. The closest pair is 1 apart, the outermost pair 2 apart.

Example 2
head=list_node([2, 5, 5, 1, 4, 4, 6, 3]) → [3, 3]

A node with an equal neighbour does not count. There are two turning nodes, 1 at position 3 and 6 at position 6, which are 3 apart.

Example 3
head=list_node([1, 2, 3]) → [-1, -1]

The values only rise, so there are no turns.

Constraints
  • The list has 2 to 10⁵ nodes
  • 1 ≤ node value ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumDrop the K-th Node From the Tail MediumTrade Places in Twos MediumMove the Tail to the Front MediumSorted List, Unique Values Only Medium
loading Python…
Input
head=list_node([4, 2, 6, 1, 3])
Expected
[1, 2]

Run checks the first 3 tests in your browser. Submit checks all 119 tests on the server, hidden ones included.