Find the Longest Equal Subarray — LeetCode 2831 Python Solution
MediumArrayHash TableBinary SearchSliding Window
- Problem
- #2831
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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 mxComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 1477Find Two Non-overlapping Sub-arrays Each With Target SumMediumLeetCode 1658Minimum Operations to Reduce X to ZeroMediumLeetCode 2009Minimum Number of Operations to Make Array ContinuousHardLeetCode 2830Maximize the Profit as the SalesmanMediumLeetCode 2841Maximum Sum of Almost Unique SubarrayMediumLeetCode 219Contains Duplicate IIEasy
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.