Count Windows of Ranked Posts Whose Median Equals a Target Rank

Last updated: November 29, 2026

Quick Overview

Given an array that is a permutation of ranks 1..n for posts in feed order and a target rank t, count the contiguous windows whose median is exactly t, where the median of an even-length window is the smaller of the two middle values.

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

0

0

0 solved


Given an array that is a permutation of ranks 1..n for posts in feed order and a target rank t, count the contiguous windows whose median is exactly t, where the median of an even-length window is the smaller of the two middle values.

A Hard prefix balance plus hashing problem. In a Meta onsite the interviewer wants the reduction from median to a balance condition, and the realization that every valid window must contain t's position.

What the Interviewer Expects
  • Notes that any window with median t must include t
  • Maps values greater than t to +1 and smaller to -1
  • Derives that valid windows have balance 0 (odd length) or 1 (even length)
  • Counts left-side balances in a map and pairs them with right-side balances
  • Gives O(n) time and O(n) space
Key Topics to Cover
prefix balance
hash map
median
subarray counting
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
  • Values are no longer distinct. What breaks?
  • Use the upper middle for even lengths instead.
  • Return the longest such window rather than the count.
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: ranks, a permutation of 1..n, and t in 1..n. Output: the number of subarrays whose sorted middle element (lower middle for even lengths) is t....

High-Level Design

Let p be the index of t. A window [i, j] must satisfy i <= p <= j. Score each other element +1 if greater than t, -1 if smaller. For odd length, t is the median iff the counts above and below ar...


Submit Your Answer
Markdown supported