BackeasyTwo PointersWipro

Midpoint Tracker on an Array Path Solution

Problem Statement

Given a zero‑indexed array nums, two pointers start at index 0. In each iteration the slow pointer moves one step forward while the fast pointer moves two steps forward. The process terminates when the fast pointer reaches or surpasses the last index of the array. Return the value stored at the index where the fast pointer stops; if the fast pointer moves beyond the array bounds, return the value at the last index.

Input: An array of integers nums. Output: A single integer representing the value at the stopping index of the fast pointer.

The algorithm runs in O(n) time and uses O(1) additional space.

Example 1
Input
[5,3,8,2,7]
Output
7

Explanation: Start: slow=0, fast=0. Step 1: slow=1, fast=2. Step 2: slow=2, fast=4. Step 3: fast would move to 6, which is beyond the last index (4). Stop. Fast is at index 4, value 7.

Example 2
Input
[1,2,3,4,5,6]
Output
6

Explanation: Start: slow=0, fast=0. Step 1: slow=1, fast=2. Step 2: slow=2, fast=4. Step 3: slow=3, fast=6. Fast index 6 exceeds last index 5, so return value at index 5, which is 6.

Constraints

  • 1 <= path.length <= 10^5
  • 1 <= path[i] <= 10^9
  • The space complexity must be O(1).
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Midpoint Tracker on an Array Path — Problem Statement & Solution Guide

Two PointersEasyRunner Technique (Fast and Slow Pointers)
TimeO(n)
|
SpaceO(1)

Problem Description

Given a zero‑indexed array nums, two pointers start at index 0. In each iteration the slow pointer moves one step forward while the fast pointer moves two steps forward. The process terminates when the fast pointer reaches or surpasses the last index of the array. Return the value stored at the index where the fast pointer stops; if the fast pointer moves beyond the array bounds, return the value at the last index.

Input: An array of integers nums.

Output: A single integer representing the value at the stopping index of the fast pointer.

The algorithm runs in O(n) time and uses O(1) additional space.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Midpoint Tracker on an Array Path"

easy

WHY DOES IT MATTER?

The two‑pointer pattern provides O(n) time with O(1) space for problems that require relative positioning (middle, cycle detection, palindrome checks). It eliminates the need for extra passes or auxiliary data structures, which is crucial in memory‑constrained or real‑time environments.

OPTIMIZATION CHALLENGE

The key insight is that the fast pointer’s double speed guarantees it will traverse the entire array in roughly half the iterations of the slow pointer, allowing the algorithm to stop as soon as the fast pointer hits the boundary, thereby avoiding any post‑processing or length calculations.

REAL-WORLD CONNECTION

Think of a conveyor belt (slow pointer) and a faster robot arm (fast pointer) scanning items. The robot arm skips ahead, and when it reaches the end of the belt, the belt’s position tells you which item is at the midpoint, mirroring how load balancers sample traffic to estimate median latency without storing every request.

During an interview, write the loop as while (fast < n) { slow++; fast += 2; } and then handle the out‑of‑bounds case immediately after the loop; this keeps the code clean and prevents off‑by‑one bugs.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The two‑pointer technique, often called the tortoise‑and‑hare algorithm, leverages two indices moving at different speeds to traverse a linear data structure in a single pass. In this problem the slow pointer advances one step while the fast pointer advances two steps; the fast pointer’s final position reveals the midpoint or the element reached after ⌈n/2⌉ steps, depending on array length. A naive solution would simulate each step with separate loops or repeatedly recompute indices, leading to O(n) time but also unnecessary overhead and potential off‑by‑one errors for large inputs. The optimal paradigm treats the fast pointer as the driver of termination: as soon as it reaches or exceeds the last index, the algorithm stops, guaranteeing linear time with constant extra space.

The elegance of this approach lies in its ability to locate a middle‑related element without auxiliary storage or multiple passes. Because the fast pointer moves twice as fast, it covers the entire array in roughly half the number of iterations of the slow pointer, making the total iteration count ⌊n/2⌋+1. This deterministic progression eliminates the need for length calculations or division, which can be costly in languages without built‑in integer division safety. Consequently, the algorithm scales gracefully to arrays with millions of elements, where any extra pass or memory allocation would be prohibitive.

Interview Questions on This Problem

Q1How would you modify the algorithm to return the value at the exact middle index for both even and odd length arrays?

Maintain the same two‑pointer traversal but, after the loop, check if the array length is odd. If odd, the fast pointer lands exactly on the middle element; if even, the slow pointer will be at the lower middle, so return nums[slow+1] or compute (nums[slow] + nums[slow+1])/2 depending on the requirement.

Q2Can you adapt this two‑pointer pattern to detect a cycle in a singly linked list? Explain the steps.

Yes. Initialize both pointers at the head; move slow by one node and fast by two nodes each iteration. If at any point fast meets slow, a cycle exists. If fast reaches null, the list terminates without a cycle. This is the classic Floyd’s cycle‑detection algorithm.

Q3In a distributed system where each node holds a segment of a large array, how would you efficiently compute the midpoint value using minimal inter‑node communication?

Each node locally runs the two‑pointer scan on its segment, reporting the count of steps taken by the fast pointer before it exits the segment. Aggregating these counts centrally determines the global step count; the node where the cumulative fast steps reach the array’s end holds the midpoint value, which can then be fetched with a single remote read.

Examples

Example 1

Input

[5,3,8,2,7]

Output

7

Explanation: Start: slow=0, fast=0. Step 1: slow=1, fast=2. Step 2: slow=2, fast=4. Step 3: fast would move to 6, which is beyond the last index (4). Stop. Fast is at index 4, value 7.

Example 2

Input

[1,2,3,4,5,6]

Output

6

Explanation: Start: slow=0, fast=0. Step 1: slow=1, fast=2. Step 2: slow=2, fast=4. Step 3: slow=3, fast=6. Fast index 6 exceeds last index 5, so return value at index 5, which is 6.

Constraints

  • 1 <= path.length <= 10^5
  • 1 <= path[i] <= 10^9
  • The space complexity must be O(1).

Optimal Approach & Strategy

Use a single loop with two pointers moving at different speeds; stop when the fast pointer reaches the end and return the element at the fast pointer’s final valid index.

Brute Force Approach

Iterate through the array to compute its length, then calculate the midpoint index with division and return the element at that index; this requires two passes over the data.

Verified Code Solutions

JavaScript Solution
Time: O(n)
/**
 * @param {number[]} nums
 * @return {number}
 */
var getMidpointValue = function(nums) {
    let n = nums.length;
    let slow = 0, fast = 0;
    while (fast < n) {
        slow++;
        fast += 2;
    }
    return nums[slow];
};

Asked in Top Tech Interviews

Wipro

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.