Ctrl K

Stretches With a Given Median

Hard
The array perm of length n is a permutation of the numbers 1 to n: each appears exactly once. You are also given a number target. The median of a group of numbers is the element in the middle once they are sorted in ascending order. When the count is even, take the left of the two middle values: the median of [7, 1, 4, 2] is 2, and the median of [6, 2, 9] is 6. Count the non-empty stretches of perm (contiguous pieces of the array) whose median equals target.
Example 1
perm=[2, 5, 3, 1, 4], target=3 → 7

Seven stretches qualify: [3], [5, 3], [2, 5, 3], [5, 3, 1], [3, 1, 4], [5, 3, 1, 4] and the whole array. For instance, [5, 3] sorts to [3, 5], and the left of its two middle values is 3. The median of [2, 5, 3, 1], however, is 2.

Example 2
perm=[1, 2], target=2 → 1

The median of [1, 2] is 1, so only [2] qualifies.

Example 3
perm=[3, 1, 2], target=1 → 3
Constraints
  • 1 ≤ n = len(perm) ≤ 10⁵
  • perm contains every number from 1 to n exactly once
  • 1 ≤ target ≤ n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFour Equal Pieces HardRectangles With a Given Sum HardA Shelf With Matching Ends HardBalanced Cuts After One Replacement HardFlowers in Bloom on Visit Day Hard
loading Python…
Input
perm=[2, 5, 3, 1, 4], target=3
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 68 tests on the server, hidden ones included.