Find the Longest Equal Subarray — LeetCode 2831 Python Solution

MediumArrayHash TableBinary SearchSliding Window
Problem
#2831
Reading time
2 min

The problem

You are given a 0-indexed integer array nums and an integer k. A subarray is called equal if all of its elements are equal.

Example

Input
nums = [1,3,2,3,1,3], k = 3
Output
3
Explanation
It's optimal to delete the elements at index 2 and index 4.

Python solution

Python
class Solution:
    def longestEqualSubarray(self, nums: List[int], k: int) -> int:
        cnt = Counter()
        l = 0
        mx = 0
        for r, x in enumerate(nums):
            cnt[x] += 1
            mx = max(mx, cnt[x])
            if r - l + 1 - mx > k:
                cnt[nums[l]] -= 1
                l += 1
        return mx

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2831. Find the Longest Equal Subarray is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2831. Find the Longest Equal Subarray?
LeetCode 2831. Find the Longest Equal Subarray is rated Medium on LeetCode.
What is the time complexity of LeetCode 2831. Find the Longest Equal Subarray?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2831. Find the Longest Equal Subarray?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2831. Find the Longest Equal Subarray cover?
LeetCode 2831. Find the Longest Equal Subarray is tagged Array, Hash Table, Binary Search and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview