2780. Minimum Index of a Valid Split #1485
-
Topics: An element You are given a 0-indexed integer array You can split
Here, Return the minimum index of a valid split. If no valid split exists, return Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the minimum index at which we can split the array such that both resulting subarrays have the same dominant element as the original array. A dominant element is one that appears more than half the time in the array. Approach
Let's implement this solution in PHP: 2780. Minimum Index of a Valid Split <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minimumIndex($nums) {
$n = count($nums);
if ($n < 2) {
return -1;
}
$x = findDominant($nums);
$total_x = 0;
foreach ($nums as $num) {
if ($num == $x) {
$total_x++;
}
}
$prefix = array();
$current = 0;
foreach ($nums as $num) {
if ($num == $x) {
$current++;
}
$prefix[] = $current;
}
for ($i = 0; $i < $n - 1; $i++) {
$left_count = $prefix[$i];
$right_count = $total_x - $left_count;
$left_length = $i + 1;
$right_length = $n - $i - 1;
if (($left_count * 2 > $left_length) && ($right_count * 2 > $right_length)) {
return $i;
}
}
return -1;
}
/**
* @param $nums
* @return mixed|null
*/
function findDominant($nums) {
$count = 0;
$candidate = null;
foreach ($nums as $num) {
if ($count == 0) {
$candidate = $num;
$count = 1;
} else {
$count += ($num == $candidate) ? 1 : -1;
}
}
return $candidate;
}
// Test cases
$test1 = [1, 2, 2, 2];
$test2 = [2, 1, 3, 1, 1, 1, 7, 1, 2, 1];
$test3 = [3, 3, 3, 3, 7, 2, 2];
echo minimumIndex($test1) . "\n"; // Output: 2
echo minimumIndex($test2) . "\n"; // Output: 4
echo minimumIndex($test3) . "\n"; // Output: -1
?> Explanation:
This approach ensures that we efficiently determine the valid split with a time complexity of O(n) and space complexity of O(n), making it suitable for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find the minimum index at which we can split the array such that both resulting subarrays have the same dominant element as the original array. A dominant element is one that appears more than half the time in the array.
Approach