Skip to content

2831. Find the Longest Equal Subarray 👍

Approach 1: Regular Window

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int longestEqualSubarray(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> count;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      ans = max(ans, ++count[nums[r]]);
      while (r - l + 1 - k > ans)
        --count[nums[l++]];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int longestEqualSubarray(List<Integer> nums, int k) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      ans = Math.max(ans, count.merge(nums.get(r), 1, Integer::sum));
      while (r - l + 1 - k > ans)
        count.merge(nums.get(l++), -1, Integer::sum);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestEqualSubarray(self, nums: list[int], k: int) -> int:
    ans = 0
    count = collections.Counter()

    l = 0
    for r, num in enumerate(nums):
      count[num] += 1
      ans = max(ans, count[num])
      while r - l + 1 - k > ans:
        count[nums[l]] -= 1
        l += 1

    return ans

Approach 2: Lazy Window

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int longestEqualSubarray(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> count;

    // l and r track the maximum window instead of the valid window.
    for (int l = 0, r = 0; r < nums.size(); ++r) {
      ans = max(ans, ++count[nums[r]]);
      if (r - l + 1 - k > ans)
        --count[nums[l++]];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int longestEqualSubarray(List<Integer> nums, int k) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    // l and r track the maximum window instead of the valid window.
    for (int l = 0, r = 0; r < nums.size(); ++r) {
      ans = Math.max(ans, count.merge(nums.get(r), 1, Integer::sum));
      if (r - l + 1 - k > ans)
        count.merge(nums.get(l++), -1, Integer::sum);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def longestEqualSubarray(self, nums: list[int], k: int) -> int:
    ans = 0
    count = collections.Counter()

    # l and r track the maximum window instead of the valid window.
    l = 0
    for r, num in enumerate(nums):
      count[num] += 1
      ans = max(ans, count[num])
      if r - l + 1 - k > ans:
        count[nums[l]] -= 1
        l += 1

    return ans