mediumArraysPattern: subarray

Longest Uniform Subarray Solution

Problem Statement

Given a sequence of integers `seq`, determine the length of the longest contiguous segment where all elements are identical. If the sequence is empty, return 0.

Examples

Example 1:
Input:[1, 1, 1, 2, 2, 3, 3, 3, 3]
Output:4
Explanation: The longest uniform subarray is [3, 3, 3, 3].
Example 2:
Input:[5, 5, 5]
Output:3
Explanation: The entire array is a uniform subarray.

Constraints

  • 1 <= seq length <= 10^5
  • -10^9 <= seq elements <= 10^9
  • seq is a list of integers
  • seq can be empty
  • seq elements are not guaranteed to be distinct
Time: O(n) Space: O(1)
The optimal approach involves scanning the sequence once and keeping track of the current uniform subarray length. When a different element is encountered, the length of the current uniform subarray is compared with the maximum length found so far and updated if necessary. This approach has a time complexity of O(n) and a space complexity of O(1), where n is the length of the sequence.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

import sys seq = list(map(int, input().split(','))) if len(seq) == 0: print(0) else: max_length = 0 current_length = 1 for i in range(1, len(seq)): if seq[i] == seq[i - 1]: current_length += 1 else: max_length = max(max_length, current_length) current_length = 1 max_length = max(max_length, current_length) print(max_length)