Paste Search Dynamic
threeEqualParts
  1. var threeEqualParts = function(arr) {
  2.     const N = arr.length
  3.     let totalones = 0
  4.     for (let i=0; i<N; i++) {
  5.         if (arr[i] == 1) totalones++
  6.     }
  7.    
  8.     if (!totalones) return [0, N-1]
  9.    
  10.     let leadingzeros = 0
  11.     for (let i=N-1; i>=0; i--) {
  12.         if (arr[i] == 0) leadingzeros++
  13.         else break
  14.     }
  15.    
  16.     if (totalones % 3 > 0) return [-1,-1]
  17.    
  18.    
  19.     const sliceones = totalones / 3
  20.    
  21.     let right = N-1
  22.    
  23.     {
  24.         let countones = 0
  25.         while (right>=0 && countones < sliceones) countones += arr[right--]
  26.         while (right>=0 && arr[right] == 0) right--
  27.         right += leadingzeros + 1;
  28.     }
  29.  
  30.     let left = right-1
  31.    
  32.     {
  33.         let countones = 0
  34.         while (left>=0 && countones < sliceones) countones += arr[left--]
  35.         while (left>=0 && arr[left] == 0) left--
  36.         left += leadingzeros;
  37.     }
  38.    
  39.     let i = 0; while (!arr[i] && i < left) i++
  40.     let j = left+1; while (!arr[j] && j < right) j++
  41.     let k = right; while (!arr[k] && k < N-1) k++
  42.    
  43.     const a = arr.slice(i, left+1)
  44.     const b = arr.slice(j, right)
  45.     const c = arr.slice(k, N)
  46.    
  47.     for (let idx = 0; idx<Math.max(a.length, b.length, c.length); idx++) {
  48.         if (a[idx] != b[idx] || a[idx] != c[idx] || b[idx] != c[idx]) return [-1, -1]
  49.     }
  50.  
  51.     return [left, right]
  52.    
  53.    
  54. };
Parsed in 0.011 seconds