Skip to content

Commit ea69169

Browse files
committed
Add solution #2780
1 parent eedf0f1 commit ea69169

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,6 +1001,7 @@
10011001
2725|[Interval Cancellation](./solutions/2725-interval-cancellation.js)|Easy|
10021002
2726|[Calculator with Method Chaining](./solutions/2726-calculator-with-method-chaining.js)|Easy|
10031003
2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy|
1004+
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
10041005
2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
10051006
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
10061007
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)