Skip to content

Commit 70cc79c

Browse files
authored
Create 927-three-equal-parts.js
1 parent b9fddf6 commit 70cc79c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

927-three-equal-parts.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number[]} A
3+
* @return {number[]}
4+
*/
5+
const threeEqualParts = function (A) {
6+
let countNumberOfOnes = 0
7+
for (let c of A) if (c === 1) countNumberOfOnes++
8+
if (countNumberOfOnes === 0) return [0, A.length - 1]
9+
if (countNumberOfOnes % 3 != 0) return [-1, -1]
10+
const k = countNumberOfOnes / 3
11+
let i
12+
// find the first 1 in the array
13+
for (i = 0; i < A.length; i++) if (A[i] == 1) break
14+
let start = i
15+
// find (k+1)th 1 in the array
16+
let count1 = 0
17+
for (i = 0; i < A.length; i++) {
18+
if (A[i] == 1) count1++
19+
if (count1 == k + 1) break
20+
}
21+
let mid = i
22+
//find (2*k +1)th 1 in the array
23+
count1 = 0
24+
for (i = 0; i < A.length; i++) {
25+
if (A[i] === 1) count1++
26+
if (count1 === 2 * k + 1) break
27+
}
28+
let end = i
29+
// Match all values till the end of the array
30+
while (end < A.length && A[start] === A[mid] && A[mid] === A[end]) {
31+
start++
32+
mid++
33+
end++
34+
}
35+
// Return appropriate values if all the values have matched till the end
36+
if (end == A.length) return [start - 1, mid]
37+
// otherwise, no such indices found
38+
return [-1, -1]
39+
}

0 commit comments

Comments
 (0)