← Uber bank

Uber · Question 3 · Arrays

Find the largest subarray with equal number of 0s and 1s

ArraysPythoncode⏱ O(n)💾 O(n)
Product-based

Problem

Find max length subarray with equal 0s and 1s.

Approach

Replace 0 with - 1, use hashmap of prefix sums.

Time O(n)Space O(n)

How it works

  1. 1Treat 0 as -1 so equal counts mean prefix sum zero.
  2. 2Record the first index of every prefix sum.
  3. 3A repeated sum marks a balanced subarray; keep the longest.

Sample input / output

Input:
3
0 1 0
Output:
2

Constraints

1 <= nums.length <= 10^5; nums[i] is 0 or 1.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatyesnoSTARTnumsprefix_sum = 0max_length = 0sum_index_map = {0: -1}for i, num inenumerate(nums)prefix_sum += -1 if num ==0 else 1if prefix_sum insum_index_mapmax_length =max(max_length, i -sum_index_map[prefix_sum])ELSEsum_index_map[prefix_sum] =iRETURN max_lengthDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))nums = [int(next(it)) for _in range(n)]print(findMaxLength(nums))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits