Longest Balanced Binary Subarray
Updated
Problem statement
Given a binary array nums, return the length of its longest contiguous subarray containing equal numbers of zeros and ones.
For this exercise, assume the array may be empty. Return 0 when no nonempty balanced subarray exists. A subarray preserves consecutive positions; choosing separated elements is not allowed.
Function
longestBalancedSubarray(nums: int[]) → intExamples
Example 1
nums = [0,1,0,0,1]return = 4The interval at indices 1 through 4 is [1,0,0,1], with two zeros and two ones. Its length is 4. A balanced length must be even, and the full array has length 5, so no longer balanced interval is possible.
Example 2
nums = [1,1,1]return = 0Every nonempty interval contains only ones, so none has equal counts of zeros and ones.
Constraints
- For this exercise, assume 0 <= nums.length <= 5000.
- Every nums[i] is either 0 or 1.
More Morgan Stanley Online Assessment questions
- Three-Resource 0/1 KnapsackOA · Seen Sep 2026
- Maximum Concurrent ProcessesOA · ONSITE INTERVIEW · Seen Sep 2026
- Maximum Total of Nonadjacent RatingsOA · Seen Jul 2026
- Count Shipment SchedulesOA · Seen Apr 2026
- Delete and EarnOA · Seen Apr 2026
- Interleave Array HalvesOA · Seen Apr 2026
- Get Patch SequenceOA · Seen Feb 2025
- String Subsequences 🐳OA · Seen Mar 2024
- Binary Tree Level OrderOA · Seen Feb 2024
- Merge IntervalsOA · Seen Feb 2024
Similar questions at other companies
- Most Visited Sprint MarkerMicrosoft · OAMicrosoft 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
- Optimal TransferSnowflake · OASnowflake interview questions
- Count Attack Vectors by Divisor RangeVisa · OAVisa interview questions
- Smallest Most-Lit Street PositionHudson River Trading · OAHudson River Trading interview questions
- Most Visited Sprint MarkerChubb · OAChubb interview questions
- Minimum Seats for One-Way Car PoolingSquadStack.ai · OA
- Shortest Path Around Rectangular ObstaclesDRW · OADRW interview questions
Interview reports that mention this question
Morgan Stanley interview experiences
- Morgan Stanley Apprenticeship and Tech Interviews: 6 Experiences
- Morgan Stanley New Grad Technology Analyst: 2 Experiences
- Morgan Stanley Intern Oldest Loops: 5 Experiences (Part 5 of 5)
- Morgan Stanley Intern Earlier Loops: 5 Experiences (Part 3 of 5)
- Morgan Stanley Intern Tech Rounds: 5 Experiences (Part 2 of 5)