Problem

Longest Equal Binary Subarray After One Flip

Learn this problem
HackerRank logoHackerRankFULLTIMEOA

Problem statement

You are given a binary array arr containing only 0s and 1s.

You may flip at most one element of the array, changing a 0 to a 1 or a 1 to a 0.

Return the length of the longest contiguous subarray that can contain an equal number of 0s and 1s after performing at most one flip.

Function

longestEqualBinarySubarrayAfterOneFlip(arr: int[]) → int

Examples

Example 1

arr = [0,1,0,0,1,1,0,0]return = 8

The whole array has five 0s and three 1s. Flip one 0 to 1 to make the counts equal.

Example 2

arr = [0,0,0,1]return = 4

Flip one 0 in the whole array, leaving two 0s and two 1s.

Example 3

arr = [1,1,1]return = 2

Any length-2 subarray can be balanced by flipping one 1 to 0.

Constraints

  • 1 <= arr.length <= 100000
  • arr[i] is either 0 or 1

More HackerRank problems

drafts saved locally
public int longestEqualBinarySubarrayAfterOneFlip(int[] arr) {
  // write your code here
}
arr[0,1,0,0,1,1,0,0]
expected8
checking account