Skip to content

2780. Minimum Index of a Valid Split 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int minimumIndex(vector<int>& nums) {
    const int n = nums.size();
    unordered_map<int, int> count1;
    unordered_map<int, int> count2;

    for (const int num : nums)
      ++count2[num];

    for (int i = 0; i < n; ++i) {
      const int freq1 = ++count1[nums[i]];
      const int freq2 = --count2[nums[i]];
      if (freq1 * 2 > i + 1 && freq2 * 2 > n - 1 - i)
        return i;
    }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int minimumIndex(List<Integer> nums) {
    final int n = nums.size();
    Map<Integer, Integer> count1 = new HashMap<>();
    Map<Integer, Integer> count2 = new HashMap<>();

    for (final int num : nums)
      count2.merge(num, 1, Integer::sum);

    for (int i = 0; i < n; ++i) {
      final int freq1 = count1.merge(nums.get(i), 1, Integer::sum);
      final int freq2 = count2.merge(nums.get(i), -1, Integer::sum);
      if (freq1 * 2 > i + 1 && freq2 * 2 > n - 1 - i)
        return i;
    }

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minimumIndex(self, nums: list[int]) -> int:
    count1 = collections.Counter()
    count2 = collections.Counter(nums)

    for i, num in enumerate(nums):
      count1[num] = count1[num] + 1
      count2[num] = count2[num] - 1
      if count1[num] * 2 > i + 1 and count2[num] * 2 > len(nums) - i - 1:
        return i

    return -1