FastPrepLongest Equal Binary Subarray After One Flip
Problems/Longest Equal Binary Subarray After One Flip

Longest Equal Binary Subarray After One Flip

HackerRank logoHackerRankFULLTIMEOA

Updated Sep 2026

QuestionFunctionExamplesConstraints

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 interview questions

  • Longest Equal Binary SubarrayOA · Seen Dec 2025
  • Longest Prefix-Valid Binary SubarrayOA · Seen May 2025
  • Classify Password StrengthPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
  • Check Permutation Divisible by EightONSITE INTERVIEW · Seen Mar 2026
  • Ball Passing at Time KPHONE SCREEN · Seen Dec 2025
All HackerRank interview questionsSee HackerRank hiring insights
Saved
class Solution {
    public int longestEqualBinarySubarrayAfterOneFlip(int[] arr) {
      // write your code here
    }
}
Checking account…