|
| 1 | +/** |
| 2 | + * 927. Three Equal Parts |
| 3 | + * https://leetcode.com/problems/three-equal-parts/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array arr which consists of only zeros and ones, divide the array into three |
| 7 | + * non-empty parts such that all of these parts represent the same binary value. |
| 8 | + * |
| 9 | + * If it is possible, return any [i, j] with i + 1 < j, such that: |
| 10 | + * - arr[0], arr[1], ..., arr[i] is the first part, |
| 11 | + * - arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and |
| 12 | + * - arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. |
| 13 | + * - All three parts have equal binary values. |
| 14 | + * |
| 15 | + * If it is not possible, return [-1, -1]. |
| 16 | + * |
| 17 | + * Note that the entire part is used when considering what binary value it represents. For example, |
| 18 | + * [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] |
| 19 | + * represent the same value. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} arr |
| 24 | + * @return {number[]} |
| 25 | + */ |
| 26 | +var threeEqualParts = function(arr) { |
| 27 | + const totalOnes = arr.reduce((sum, num) => sum + num, 0); |
| 28 | + if (totalOnes % 3 !== 0) { |
| 29 | + return [-1, -1]; |
| 30 | + } |
| 31 | + if (totalOnes === 0) { |
| 32 | + return [0, arr.length - 1]; |
| 33 | + } |
| 34 | + |
| 35 | + const onesPerPart = totalOnes / 3; |
| 36 | + let firstStart = -1; |
| 37 | + let secondStart = -1; |
| 38 | + let thirdStart = -1; |
| 39 | + let onesCount = 0; |
| 40 | + for (let i = 0; i < arr.length; i++) { |
| 41 | + if (arr[i] === 1) { |
| 42 | + onesCount++; |
| 43 | + if (onesCount === 1) firstStart = i; |
| 44 | + if (onesCount === onesPerPart + 1) secondStart = i; |
| 45 | + if (onesCount === 2 * onesPerPart + 1) thirdStart = i; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + const patternLength = arr.length - thirdStart; |
| 50 | + if (secondStart - firstStart < patternLength || thirdStart - secondStart < patternLength) { |
| 51 | + return [-1, -1]; |
| 52 | + } |
| 53 | + for (let i = 0; i < patternLength; i++) { |
| 54 | + if (arr[firstStart + i] !== arr[secondStart + i] |
| 55 | + || arr[firstStart + i] !== arr[thirdStart + i]) { |
| 56 | + return [-1, -1]; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + const i = firstStart + patternLength - 1; |
| 61 | + const j = secondStart + patternLength; |
| 62 | + |
| 63 | + return [i, j]; |
| 64 | +}; |
0 commit comments