Problem Description
Given a 0-indexed integer array nums that has exactly one dominant element (an element that appears more than half of the time in the array), find the minimum index i (with 0 <= i < n - 1) to split nums into two non-empty subarrays such that both subarrays have the same dominant element as nums. If no valid split exists, return -1.
Key Insights
- The entire array has exactly one dominant element. This element must be the dominant one in both subarrays if a valid split exists.
- Start by identifying the dominant element by counting its total occurrences in nums.
- While iterating through the array indices, maintain a running count (prefix sum) of the dominant element.
- For a split at index i to be valid:
- The dominant element should appear more than (i + 1) / 2 times in the left subarray.
- The remaining occurrences in the right subarray must be more than (n - i - 1) / 2.
- The problem can be solved in one pass through the array after counting the total occurrences, resulting in an overall O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1) (excluding input space)
Solution
The solution begins by finding the dominant element in the entire nums array by counting its occurrences. During a single traversal (from index 0 to n-2), we maintain a prefix count of the dominant element. At each possible split index i, we check if the count in the left subarray is more than half the length of the left subarray and if the remaining count in the right subarray is more than half the length of the right subarray. The first valid index i is returned. If no valid split is found, return -1.