KatInterview

Tracking Aligned Prefix Moments in a Permutation Sequence

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingpermutationsprefix-conditionrunning-maximum

Last updated

Tests the ability to recognize when a running maximum equals the current index in a permutation, using invariant reasoning to avoid simulation.

You are given a permutation sequence of the integers from 1 to n. Imagine processing this permutation one element at a time from left to right. After processing the first k elements, you have seen exactly k distinct values from the permutation.

A moment is aligned if, after processing the first k elements, the maximum value seen so far is exactly k. In other words, the k values you have encountered are precisely the integers 1, 2, 3, ..., k (though possibly in a different order within those first k positions).

Your task is to count how many aligned moments occur as you process the entire sequence.

Constraints

  • 1 <= n == len(sequence) <= 5 * 10^4
  • sequence is a permutation of integers from 1 to n (each integer appears exactly once)

Notes

  • You check for alignment after processing each element
  • The final position (after processing all n elements) is always aligned, since you will have seen all values 1 through n

Examples

Example 1

Input: count_aligned_moments([2, 1, 3, 5, 4])

Output: 3

Example 2

Input: count_aligned_moments([3, 1, 2])

Output: 1

Example 3

Input: count_aligned_moments([1, 2, 3, 4])

Output: 4

Hints

Hint 1

After processing k elements of a permutation, you've seen exactly k distinct values. What does it mean for those k values to form a contiguous range starting from 1?

Hint 2

If the maximum value in the first k elements equals k, what can you deduce about which specific values those k elements must be?

Hint 3

You don't need to track which values you've seen—only track the running maximum and compare it to the current position.