[Interview][FAANG] Ways of dividing an array into sub-sections having half of 1s and half of 0s

Q: Given an array of 0s and 1s. Count of 0s and 1s are always even. Find all ways of dividing an array into sub-sections having half of 1s and half of 0s.

eg:
11110000
total 1s = 4 & 0s = 4. So each sub-sections in the result must have two 1s and two 0s.
output: 1100

1101100110
output:
10110
11001
10011

my approach:

  1. First store count of 0s and 1s till each index 'i'
  2. take two pointers left =0 and right = arr.length-1 and run a loop and subtract arr[right]-arr[left]. Add 1 if current element is 1
  3. repeat step 2 for 0s
  4. Store locations of left and right in two lists for 1s and 0s such that difference of count = half (for both 0s and 1s)
  5. Find point of intersection of lists in step-4 and return the list

I could not solve it completely though.

Can anyone help me in working on solution for this problem?

Comments (7)