FastPrepLongest Prefix-Valid Binary Subarray
Problems/Longest Prefix-Valid Binary Subarray

Longest Prefix-Valid Binary Subarray

HackerRank logoHackerRank● MediumFULLTIMEOA

Updated Sep 2026

QuestionFunctionExamplesConstraints

Problem statement

Source note: Reported in a HackerRank Backend Engineer II online assessment where an integrated AI interviewer introduced this task as the second follow-up to a binary-array question.

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

A contiguous subarray is prefix-valid when every non-empty prefix of that subarray contains at least as many 1s as 0s.

Return the length of the longest prefix-valid contiguous subarray. If no non-empty prefix-valid subarray exists, return 0.

Function

longestPrefixValidBinarySubarray(arr: int[]) → int

Examples

Example 1

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

The subarray [1,0,1,0] is prefix-valid: its prefix balances of 1s minus 0s are 1, 0, 1, 0. Extending it by the final 0 makes the balance negative.

Example 2

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

The longest valid choice starts at index 1: [1,1,0] has prefix balances 1, 2, 1.

Example 3

arr = [0,0,0]return = 0

Every non-empty subarray starts with 0, so its first prefix already has more 0s than 1s.

Constraints

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

More HackerRank interview questions

  • REST API: Country CodesOA · Seen Nov 2026
  • Auction Lot Bid SummaryOA · Seen Nov 2026
  • Classify Password StrengthOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
  • Longest Equal Binary SubarrayOA · Seen Dec 2025
  • Longest Equal Binary Subarray After One FlipOA · Seen Dec 2025
  • Check Permutation Divisible by EightONSITE INTERVIEW · Seen Mar 2026
  • Ball Passing at Time KPHONE SCREEN · Seen Dec 2025

Similar questions at other companies

  • Count Lamps Lighting Each PointAirbnb · OAAirbnb interview questions
  • Maximum Game Score with Fixed Forward JumpsStripe · OAStripe interview questions
  • Most Visited Sprint MarkerMicrosoft · OAMicrosoft interview questions
  • Split a Matrix Into Four Partitions by Average (Forward Deployed Engineer)Boston Consulting Group · OABoston Consulting Group interview questions
  • Earliest Time to Schedule a MeetingMathWorks · OAMathWorks interview questions
  • Earliest Meeting Start on a 24-Hour ClockIMC Trading · OAIMC Trading interview questions
  • Calculate the Sum After Range TogglesBlink Health · OA
  • Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW
  • Sum of Subarray MinimumsNVIDIA · OANVIDIA interview questions
  • Optimal TransferSnowflake · OASnowflake interview questions
All HackerRank interview questionsSee HackerRank hiring insights
Saved
class Solution {
    public int longestPrefixValidBinarySubarray(int[] arr) {
      // write your code here
    }
}
Checking account…