As reported: IBM Associate System Engineer, campus placement (India, 2026), offline coding assessment on HackerRank with two questions. Question 1 worked on a binary array.
You are given an array arr of 0s and 1s. Return the length of the longest contiguous subarray that satisfies both:
- it contains the same number of
0s and1s, and - in every prefix of the subarray, the number of
1s is at least the number of0s.
Return 0 if no non-empty subarray qualifies.
Example
arr = [1,0,1,1,0,0,1] -> 6
[1,0,1,1,0,0] (indices 0–5) has three 1s and three 0s, and its prefixes have balances 1,0,1,2,1,0, never negative.
Constraints: 1 ≤ n ≤ 10^5; arr[i] ∈ {0, 1}.
Code runner format: one JSON value per line: arr. Implement longestBalanced(arr); the harness prints the length.