#C10264. Longest Subarray with Equal Number of 0's and 1's
Longest Subarray with Equal Number of 0's and 1's
Longest Subarray with Equal Number of 0's and 1's
You are given a binary string S
consisting only of characters '0' and '1'. Your task is to find the length of the longest contiguous subarray that has an equal number of 0's and 1's.
Problem Statement:
Given a binary string S
, determine the maximum length of a subarray (continuous segment) where the number of 0's is equal to the number of 1's. If no such subarray exists, output 0.
Example:
- For
S = "1100011"
, the longest subarray with equal number of 0's and 1's has length 6. - For
S = "000000"
, there is no subarray with equal number of 0's and 1's, so the output is 0.
The solution should be efficient and able to handle large input sizes.
Hint:
You may use a hashmap (or dictionary) to store the first occurrence of a particular running count difference. Use the technique of prefix sum where you increment the count for '1' and decrement for '0'.
inputFormat
The input consists of a single line containing the binary string S
(only characters '0'
and '1'
). Input is provided from stdin
.
outputFormat
Output a single integer which is the length of the longest contiguous subarray with equal number of 0's and 1's. The result should be printed to stdout
.
1100011
6