Largest subarray with equal number of 0s and 1s in C++


Let's see the steps to complete the program.

  • Initialise the array.
  • Make all zeroes in the array to -1.
  • Have a map an empty map to store the previous indexes.
  • Initialise sum to 0, max length to 0 and ending index to -1.
  • Write a loop that iterates till n.
    • Add current element to sum.
    • If the sum is equal to 0.
      • Update the max length with i + 1.
      • And ending index to i.
    • If the sum is present in previous sums map and i - previousIndexes[sum] is greater than max length.
      • Update the max length and ending index.
    • Else add the sum to the previous indexes map.
  • Print the starting index endingIndex - maxLength + 1 and ending index endingIndex.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findTheSubArray(int arr[], int n) {
   unordered_map<int, int> previousIndexes;
   int sum = 0, maxLength = 0, endingIndex = -1;
   for (int i = 0; i < n; i++) {
      arr[i] = arr[i] == 0 ? -1 : 1;
   }
   for (int i = 0; i < n; i++) {
      sum += arr[i];
      if (sum == 0) {
         maxLength = i + 1;
         endingIndex = i;
      }
      if (previousIndexes.find(sum) != previousIndexes.end()) {
         if (maxLength < i - previousIndexes[sum]) {
            maxLength = i - previousIndexes[sum];
            endingIndex = i;
         }
      }else {
         previousIndexes[sum] = i;
      }
   }
   cout << endingIndex - maxLength + 1 << " " << endingIndex << endl;
}
int main() {
   int arr[] = { 1, 1, 0, 0, 0, 1, 1, 1, 0 };
   findTheSubArray(arr, 9);
   return 0;
}

Output

If you run the above code, then you will get the following result.

1 8

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements