#2780

Minimum Index of a Valid Split

pupil · 490 · lc medium +27 · verified · 75.5% accepted · 818 likes · top 86%

Description

An element x of integer array arr is dominant when its count exceeds half the array length.

A 0-indexed integer array nums of length n has exactly one dominant element. Splitting nums at index i yields nums[0, ..., i] and nums[i + 1, ..., n - 1]; the split is valid when:

- 0 <= i < n - 1

- Both halves share the same dominant element.

Here nums[i, ..., j] denotes the subarray from index i to index j inclusive; if j < i it is empty.

Return the smallest valid split index, or -1 if no valid split exists.

Example 1:

Input: nums = [1,2,2,2]
Output: 2
Explanation: We can split the array at index 2 to obtain arrays [1,2,2] and [2].
In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 > 3.
In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 > 1.
Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split.
It can be shown that index 2 is the minimum index of a valid split.

Example 2:

Input: nums = [2,1,3,1,1,1,7,1,2,1]
Output: 4
Explanation: We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1].
In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.
In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.
Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split.
It can be shown that index 4 is the minimum index of a valid split.

Example 3:

Input: nums = [3,3,3,3,7,2,2]
Output: -1
Explanation: It can be shown that there is no valid split.

Code

1
2
3