KatInterview

Suffix Maximum Frequency Count

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingarrayssuffix-queriessingle-pass

Last updated

Computes how many times the largest element appears in each suffix of an array using a single backward scan.

You are given an array nums containing n integers. For each position i in the array, determine how many times the largest value in the suffix starting at i appears within that suffix.

More formally, for each index i (0 ≤ i < n), find the maximum element in the subarray nums[i..n-1], then count how many times that maximum appears in the same subarray.

Return an array where the element at index i contains this count for the suffix starting at position i.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1

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

Output: [3, 2, 2, 1, 1]

Example 2

Input: count_suffix_max_occurrences([5, 5, 5, 5])

Output: [4, 3, 2, 1]

Example 3

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

Output: [1, 1, 1, 1, 1]

Hints

Hint 1

Think about processing the array from right to left—each suffix builds on the previous one by adding one element at the front.

Hint 2

Track two pieces of information as you scan backward: the current suffix's maximum value and how many times it occurs.

Hint 3

When you encounter a value larger than the current maximum, the old maximum becomes irrelevant for this new suffix.