Difference of Segment Extremes — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Iterating arrays and tracking min/max

TopicArrays
PatternBasic Traversal
TimeO(n)
SpaceO(1)

Problem Description

You are provided with an integer array nums of even length n. The array is conceptually divided into two contiguous segments of equal size: the first half (indices 0 to n/2 - 1) and the second half (indices n/2 to n - 1).

Your task is to compute the difference between the maximum element found in the first half and the minimum element found in the second half. Specifically, let maxFirst be the largest value in the first segment and minSecond be the smallest value in the second segment. Return the value maxFirst - minSecond.

This operation requires a single linear pass through the array to identify the relevant extrema within their respective boundaries.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Difference of Segment Extremes"

easy

WHY DOES IT MATTER?

This pattern demonstrates how to solve a problem with a single linear scan by maintaining running extrema, a common interview theme that tests understanding of time‑space trade‑offs and efficient data aggregation.

OPTIMIZATION CHALLENGE

The key insight is that the two halves are independent, so you can compute their extrema in parallel within the same loop, eliminating the need for sorting or nested comparisons.

REAL-WORLD CONNECTION

Consider a load balancer that needs to find the busiest server in the first half of a rack and the least busy server in the second half; it can do so by inspecting each server once, rather than sorting all load metrics.

When explaining this to an interviewer, emphasize that you’re leveraging the fact that the array is split into two contiguous segments, so you can treat each segment separately while still iterating only once.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem reduces to a single linear scan of the array, maintaining two values: the maximum of the first half and the minimum of the second half. A naive solution might sort each half or use nested loops to compare every pair, leading to O(n log n) or O(n^2) time, which is unnecessary and costly for large inputs. By iterating once, we update the maximum when encountering an element in the first half and update the minimum when encountering an element in the second half, achieving optimal O(n) time and O(1) auxiliary space. This pattern exemplifies the divide‑and‑conquer principle applied to contiguous segments without explicit recursion, leveraging the fact that the halves are independent and can be processed in a single pass.

Interview Questions on This Problem

Q1How would you modify the algorithm if the array length were odd and you needed to compare the maximum of the first floor(n/2) elements with the minimum of the remaining elements?

You would still perform a single pass, but the split point becomes floor(n/2). For odd n, the first half has one fewer element than the second, so you compute max over indices 0 to floor(n/2)-1 and min over floor(n/2) to n-1. The logic remains the same; only the indices change.

Q2In a distributed system where the array is sharded across multiple nodes, how can you compute the global difference efficiently?

Each node computes its local max for the first half of its shard and local min for the second half. Then a reduce operation aggregates the global max (max of all local maxes) and global min (min of all local mins). Finally, the difference is computed locally on any node. This requires only two aggregation steps and constant additional communication.

Q3What would be the impact on time complexity if you were required to return the indices of the max and min elements instead of just the difference?

The algorithm still runs in O(n) time because you can track indices alongside values during the single pass. The additional bookkeeping does not change asymptotic complexity, only constant factors.

Examples

Example 1

Input

nums = [5, 2, 8, 1, 4, 3]

Output

7

Explanation: The array length is 6, so the split occurs at index 3. The first half is [5, 2, 8] and the second half is [1, 4, 3]. The maximum value in the first half is 8. The minimum value in the second half is 1. The difference is 8 - 1 = 7.

Example 2

Input

nums = [-10, -20, -5, -15, -25, -30]

Output

20

Explanation: The first half is [-10, -20, -5] and the second half is [-15, -25, -30]. The maximum value in the first half is -5. The minimum value in the second half is -30. The difference is -5 - (-30) = -5 + 30 = 25. Wait, let me re-calculate. Max of [-10, -20, -5] is -5. Min of [-15, -25, -30] is -30. -5 - (-30) = 25. Let me adjust the example to be simpler or correct the math. Let's use nums = [10, 20, 30, 5, 15, 25]. First half [10, 20, 30], max is 30. Second half [5, 15, 25], min is 5. 30 - 5 = 25. Let's stick to the previous one but correct the output. -5 - (-30) = 25. So output should be 25.

Example 3

Input

nums = [1, 1, 1, 1, 1, 1]

Output

0

Explanation: The first half is [1, 1, 1] and the second half is [1, 1, 1]. The maximum value in the first half is 1. The minimum value in the second half is 1. The difference is 1 - 1 = 0.

Example 4

Input

nums = [100, 50, 75, 10, 20, 30]

Output

90

Explanation: The first half is [100, 50, 75] and the second half is [10, 20, 30]. The maximum value in the first half is 100. The minimum value in the second half is 10. The difference is 100 - 10 = 90.

Constraints

  • 2 <= nums.length <= 10^5
  • nums.length is even
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Traverse the array once, updating a running maximum for the first half and a running minimum for the second half, then compute the difference in O(n) time and O(1) space.

Brute Force Approach

A naive approach would sort each half separately and then pick the last element of the first sorted half and the first element of the second sorted half, costing O(n log n) time.

Code Solutions

JavaScript Solution
Time: O(n)
function differenceOfSegmentExtremes(nums) {
    const n = nums.length;
    if (n < 2) return 0;
    const mid = Math.floor(n / 2);
    let maxFirst = -Infinity;
    let minSecond = Infinity;
    for (let i = 0; i < mid; i++) {
        maxFirst = Math.max(maxFirst, nums[i]);
    }
    for (let i = mid; i < n; i++) {
        minSecond = Math.min(minSecond, nums[i]);
    }
    return maxFirst - minSecond;
}

Asked in Top Tech Interviews

Swiggy

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.