Longest Uniform Subarray — Problem Statement & Solution Guide

ArraysMediumsubarray
TimeO(n)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Arrays and solve the Longest Uniform Subarray problem optimally.

TopicArrays
Patternsubarray
TimeO(n)
SpaceO(1)

Problem Description

You are provided with an integer array nums. Your task is to identify the maximum length of a contiguous subarray in which every element is identical. A uniform subarray is defined as a sequence of consecutive elements where nums[i] == nums[i+1] == ... == nums[j] for all indices from i to j.

If the input array is empty, the function should return 0. Otherwise, return the length of the longest such segment found within the array. The solution must efficiently scan the array to determine this maximum length without unnecessary overhead.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Longest Uniform Subarray"

medium

WHY DOES IT MATTER?

Detecting longest uniform segments is a building block for compression, run‑length encoding, and pattern detection in logs. Mastering this pattern teaches you to recognize when a problem's state can be summarized by a few variables, eliminating the need for nested loops.

OPTIMIZATION CHALLENGE

The key insight is that the answer depends only on transitions between different values. By updating a counter only at those transition points, you avoid recomputing lengths for overlapping subarrays, collapsing O(n^2) work into O(n).

REAL-WORLD CONNECTION

Think of a network packet stream where consecutive packets of the same type are batched together for efficient processing. Identifying the longest batch reduces overhead, similar to how the algorithm groups identical array entries.

During an interview, write the loop that tracks "prev", "currLen", and "maxLen" first; then add the edge‑case handling for an empty array. This order mirrors the mental model and reduces bugs.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem asks for the longest contiguous segment where all elements are equal. A naïve solution would examine every possible subarray, checking if all elements match, which leads to O(n^2) time and quickly becomes infeasible for large inputs (n up to 10^5 or more). The optimal approach leverages the fact that uniformity can be detected in a single linear scan: as we iterate, we keep a running count of the current streak of identical values and reset it whenever the value changes. This greedy, one‑pass technique exploits the array's inherent order and guarantees that the longest streak is captured without revisiting elements.

The algorithm belongs to the "sliding window" or "two‑pointer" family, though in its simplest form it only needs a single pointer and a counter. By maintaining only constant‑size state (current value, current length, and maximum length), we achieve O(1) auxiliary space. This pattern is a classic example of converting a combinatorial search into a deterministic scan by recognizing that the optimal substructure (the longest uniform block) can be built incrementally.

Interview Questions on This Problem

Q1How would you modify the solution to also return the start index of the longest uniform subarray?

Track the start index of the current streak and update a bestStart variable whenever a new maximum length is found. When the current element differs, reset currentStart to the current index.

Q2If the array is streamed (you cannot store the entire array), can you still compute the longest uniform subarray length?

Yes. Since the algorithm only needs the previous element and the current streak length, you can maintain those two variables while reading the stream, updating the maximum length on the fly.

Q3What changes are required to find the longest subarray where the difference between any two elements is at most 1?

You need a sliding window with a frequency map (or two counters) to keep track of the two possible values in the window, expanding the right pointer while the window satisfies max-min ≤ 1, and shrinking from the left when it violates the condition.

Examples

Example 1

Input

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

Output

3

Explanation: The array contains the following uniform segments: [1, 1] (length 2), [2] (length 1), [3, 3, 3] (length 3), and [4] (length 1). The longest segment is [3, 3, 3], which has a length of 3.

Example 2

Input

nums = [5, 5, 5, 5]

Output

4

Explanation: All elements in the array are identical. Therefore, the entire array constitutes a single uniform subarray of length 4.

Example 3

Input

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

Output

1

Explanation: No two adjacent elements are equal. Each element forms its own uniform subarray of length 1. The maximum length is therefore 1.

Example 4

Input

nums = []

Output

0

Explanation: The input array is empty. By definition, the length of the longest uniform subarray in an empty array is 0.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Traverse once, maintaining a current streak length and updating the maximum whenever the streak ends or the array finishes.

Brute Force Approach

Check every possible subarray, verify if all elements are equal, and keep the longest length found.

Code Solutions

JavaScript Solution
Time: O(n)
/**
 * @param {number[]} nums
 * @return {number}
 */
var longestUniformSubarray = function(nums) {
    if (nums.length === 0) return 0;
    let maxLen = 1;
    let currentLen = 1;
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] === nums[i - 1]) {
            currentLen++;
        } else {
            currentLen = 1;
        }
        maxLen = Math.max(maxLen, currentLen);
    }
    return maxLen;
};

Asked in Top Tech Interviews

PhonePe

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.