Problem
An element x
of an integer array arr
of length m
is dominant if more than half the elements of arr
have a value of x
.
You are given a 0-indexed integer array nums
of length n
with one dominant element.
You can split nums
at an index i
into two arrays nums[0, ..., i]
and nums[i + 1, ..., n - 1]
, but the split is only valid if:
0 <= i < n - 1
nums[0, ..., i]
, andnums[i + 1, ..., n - 1]
have the same dominant element.
Here, nums[i, ..., j]
denotes the subarray of nums
starting at index i
and ending at index j
, both ends being inclusive. Particularly, if j < i
then nums[i, ..., j]
denotes an empty subarray.
Return the minimum index of a valid split. If no valid split exists, return -1
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
nums
has exactly one dominant element.
Solution
Method 1 - Using Majority element
Here is the approach:
- Identify the dominant element: Using a voting algorithm (like Boyer-Moore Majority Voting Algorithm), we find the dominant element
x
of the arraynums
. - Count occurrences: Once we identify the dominant element
x
, we calculate its total count in the array. - Iterate for split: We iterate through the array, maintaining a count of occurrences of
x
in the left part (nums[0, ..., i]
). Check for each valid split indexi
whether both parts havex
as dominant:- Left part is valid if
left_count > (i + 1) / 2
. - Right part is valid if
(total_count - left_count) > (n - i - 1) / 2
. - If both conditions are satisfied, we update the answer to the index
i
.
- Left part is valid if
- Edge case: If no valid split exists, return
-1
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, as we perform a single pass to find the dominant element and another pass to calculate the split. - 🧺 Space complexity:
O(1)
, as we only use a few integer variables.