Created
March 27, 2025 20:04
-
-
Save tatsuyax25/03a0360df43712c956421cfd0a65089d to your computer and use it in GitHub Desktop.
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 arra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds the minimum index to split the array such that both subarrays | |
* have the same dominant element. | |
* | |
* @param {number[]} nums - The input array of integers. | |
* @return {number} - The minimum index of a valid split, or -1 if no valid split exists. | |
*/ | |
var minimumIndex = function(nums) { | |
const n = nums.length; | |
// Step 1: Identify the dominant element in the array. | |
// The "dominant" element is the one that appears more than half the time. | |
let dominant = 0; // Candidate for the dominant element. | |
let count = 0; // Tracks occurrences of the candidate. | |
for (let num of nums) { | |
if (num === dominant) { | |
count += 1; // Increment if the current number matches the candidate. | |
} else if (count === 0) { | |
dominant = num; // Update candidate when no current count. | |
count = 1; | |
} else { | |
count -= 1; // Decrement count when num differs from the candidate. | |
} | |
} | |
// Step 2: Count the total occurrences of the dominant element in the array. | |
let second_half = 0; // Total count of the dominant element. | |
for (let i = 0; i < n; i++) { | |
if (nums[i] === dominant) { | |
second_half += 1; | |
} | |
} | |
// Step 3: Find the smallest valid split index. | |
let first_half = 0; // Count of the dominant element in the left subarray. | |
for (let i = 0; i < n; i++) { | |
if (nums[i] === dominant) { | |
first_half += 1; // Increment count in the left subarray. | |
second_half -= 1; // Decrement count in the right subarray. | |
// Check if both subarrays have the dominant element as dominant. | |
if (first_half > (i + 1) / 2 && second_half > (n - 1 - i) / 2) { | |
return i; // Valid split found at index i. | |
} | |
} | |
} | |
// If no valid split is found, return -1. | |
return -1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment