Leetcode 2780: Minimum Index of a Valid Split

grid47
grid47
Exploring patterns and algorithms
Feb 3, 2024 7 min read

Given a 0-indexed integer array nums of length n, an element x in nums is called dominant if freq(x) * 2 > n, where freq(x) is the number of occurrences of x in nums. It is guaranteed that nums contains exactly one dominant element. You can split nums into two non-empty subarrays at an index i such that the dominant element of the entire array is also the dominant element of both subarrays. Find the minimum index i where this condition holds, or return -1 if no such index exists.
Problem
Approach
Steps
Complexity
Input: An integer array nums with a single dominant element.
Example: nums = [4, 5, 5, 5, 7, 5]
Constraints:
• 1 <= nums.length <= 100,000
• 1 <= nums[i] <= 1,000,000,000
• nums contains exactly one dominant element.
Output: Return the minimum index where the array can be split such that both subarrays share the same dominant element. Return -1 if no valid split exists.
Example: Output: 3
Constraints:
• Output is an integer.
• If no split exists, return -1.
Goal: Determine the smallest index i where nums can be split into two subarrays that both retain the dominant element.
Steps:
• Count the frequency of each element to identify the dominant element in nums.
• Track the cumulative frequency of the dominant element as you iterate through nums.
• For each potential split point i, calculate the frequency of the dominant element in both subarrays.
• Check if the dominant element satisfies the dominance condition in both subarrays.
• Return the smallest index i that meets the criteria or -1 if no valid split exists.
Goal: Limits and guarantees for the problem.
Steps:
• The input array nums is guaranteed to have exactly one dominant element.
• The length of nums does not exceed 100,000.
• Elements in nums are within the range [1, 1,000,000,000].
Assumptions:
• The array is not empty.
• There is exactly one dominant element in the array.
Input: nums = [4, 4, 4, 5, 6, 4]
Explanation: The dominant element is 4. The array can be split at index 2 into subarrays [4, 4, 4] and [5, 6, 4]. Both subarrays have the same dominant element, 4. Minimum valid split index is 2.

Input: nums = [2, 3, 3, 3, 4, 3, 3]
Explanation: The dominant element is 3. The array can be split at index 3 into subarrays [2, 3, 3, 3] and [4, 3, 3]. Both subarrays have the same dominant element, 3. Minimum valid split index is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus