Longest Stretch Where Likes and Unlikes Exactly Balance

Last updated: November 29, 2026

Quick Overview

Given a sequence of events where 1 means a like and 0 means an unlike on a post, return the length of the longest contiguous stretch containing equal numbers of likes and unlikes.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given a sequence of events where 1 means a like and 0 means an unlike on a post, return the length of the longest contiguous stretch containing equal numbers of likes and unlikes.

A Meta onsite question that checks whether you can turn a counting condition into a prefix sum equality and remember the first index of each value. It is a good filter for candidates who only know sliding windows, since the window is not monotone here.

What the Interviewer Expects
  • Maps 0 to -1 so balance becomes a running sum of zero
  • Stores the first index at which each running sum appears
  • Seeds sum 0 at index -1 to catch stretches that start at the beginning
  • Explains why a sliding window does not apply
  • Gives O(n) time and O(n) space
Key Topics to Cover
prefix sum
hash map
first occurrence
balance tracking
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Generalize to three reaction types where all three counts must be equal.
  • Return the start and end of the best stretch.
  • Count all balanced stretches instead of finding the longest.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: events, a list of 0s and 1s, length up to 10^5. Output: the length of the longest subarray with as many 1s as 0s, or 0 if none....

High-Level Design

Treat a like as +1 and an unlike as -1. A stretch is balanced exactly when its sum is zero, which happens when the running balance at its end equals the running balance just before its start. So scan ...


Submit Your Answer
Markdown supported