File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments