BackeasyTwo Pointers

Midpoint Tracker on an Array Path Solution

Problem Statement

You are given a 0-indexed array of integers representing a path of checkpoints. You place a slow pointer and a fast pointer at the start of the path (index 0). In each step, the slow pointer moves forward by 1 index, while the fast pointer moves forward by 2 indexes. This process continues until the fast pointer reaches or exceeds the last index of the array. Return the value of the checkpoint where the slow pointer stops.

Example 1
Input
path = [1, 2, 3, 4, 5]
Output
3

Explanation: Initially, slow = 0, fast = 0. Step 1: slow moves to index 1, fast moves to index 2. Step 2: slow moves to index 2, fast moves to index 4. Since fast has reached the last index (4), the process stops. The value at slow index 2 is 3.

Example 2
Input
path = [10, 20, 30, 40]
Output
30

Explanation: Initially, slow = 0, fast = 0. Step 1: slow moves to index 1, fast moves to index 2. Step 2: slow moves to index 2, fast moves to index 4. Since fast index 4 exceeds the last index (3), the process stops. The value at slow index 2 is 30.

Constraints

  • 1 <= path.length <= 10^5
  • 1 <= path[i] <= 10^9
  • The space complexity must be O(1).
Live Compiler
Sign InSign Up
Loading...
Test Cases & Output
Click "Run" to execute