|
| 1 | +/** |
| 2 | + * 2780. Minimum Index of a Valid Split |
| 3 | + * https://leetcode.com/problems/minimum-index-of-a-valid-split/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * An element x of an integer array arr of length m is dominant if more than half the elements |
| 7 | + * of arr have a value of x. |
| 8 | + * |
| 9 | + * You are given a 0-indexed integer array nums of length n with one dominant element. |
| 10 | + * |
| 11 | + * You can split nums at an index i into two arrays nums[0, ..., i] and nums[i + 1, ..., n - 1], |
| 12 | + * but the split is only valid if: |
| 13 | + * - 0 <= i < n - 1 |
| 14 | + * - nums[0, ..., i], and nums[i + 1, ..., n - 1] have the same dominant element. |
| 15 | + * |
| 16 | + * Here, nums[i, ..., j] denotes the subarray of nums starting at index i and ending at index j, |
| 17 | + * both ends being inclusive. Particularly, if j < i then nums[i, ..., j] denotes an empty subarray. |
| 18 | + * |
| 19 | + * Return the minimum index of a valid split. If no valid split exists, return -1. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} nums |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var minimumIndex = function(nums) { |
| 27 | + const map = new Map(); |
| 28 | + |
| 29 | + for (const num of nums) { |
| 30 | + map.set(num, (map.get(num) || 0) + 1); |
| 31 | + } |
| 32 | + |
| 33 | + let dominantElement; |
| 34 | + for (const [num, count] of map) { |
| 35 | + if (count * 2 > nums.length) { |
| 36 | + dominantElement = num; |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let leftCount = 0; |
| 42 | + for (let i = 0; i < nums.length - 1; i++) { |
| 43 | + leftCount += nums[i] === dominantElement ? 1 : 0; |
| 44 | + const rightCount = map.get(dominantElement) - leftCount; |
| 45 | + |
| 46 | + if (leftCount * 2 > i + 1 && rightCount * 2 > nums.length - i - 1) { |
| 47 | + return i; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return -1; |
| 52 | +}; |
0 commit comments