Count Valid Suffix Sorts I Problem
Description
LeetCode Problem 4107.
You are given two integer arrays nums and target, both of length n.
For each index i, consider sorting the suffix nums[i..n - 1] of the original array in non-increasing order.
Return the number of indices i for which the resulting array is equal to target.
A suffix of an array is a subarray that begins at any index and extends to the end of the array.
Example 1:
Input: nums = [1,2,3], target = [3,2,1]
Output: 1
Explanation:
- i = 0: The resulting array is [3, 2, 1], which equals target.
- i = 1: The resulting array is [1, 3, 2].
- i = 2: The resulting array is [1, 2, 3].
Only i = 0 is valid, so the answer is 1.
Example 2:
Input: nums = [1,5,6,4,6], target = [1,5,6,6,4]
Output: 2
Explanation:
Choosing either i = 2 or i = 3 results in [1, 5, 6, 6, 4]. No other index produces target. Therefore, the answer is 2.
Example 3:
Input: nums = [7,6,8], target = [8,6,7]
Output: 0
Explanation:
Sorting the suffix starting at indices 0, 1, and 2 produces [8, 7, 6], [7, 8, 6], and [7, 6, 8], respectively. None equals target, so the answer is 0.
Constraints:
1 <= n == nums.length == target.length <= 10^51 <= nums[i], target[i] <= 10^5
Solution
Approach: Prefix and Last Ascent
Sorting the suffix from i leaves nums[0..i) unchanged and keeps the multiset of the whole array. So the answer is 0 unless nums and target contain the same numbers; check this with a count table.
If they do, i is valid exactly when:
nums[0..i)equalstarget[0..i), which meansiis at most the first indexmaxIwhere the arrays differ (maxI = n - 1if they are equal), andtarget[i..n)is non-increasing, which meansiis at leastminI, the index of the last ascenttarget[i-1] < target[i](0if there is none).
Given equal prefixes and equal multisets, the two suffixes have the same multiset too, so a non-increasing target[i..n) is exactly the sorted suffix. Every i in [minI, maxI] works, so the answer is max(maxI - minI + 1, 0).
Complexity: O(n) time and O(n) space.
class Solution:
def countSuffix(self, nums: List[int], target: List[int]) -> int:
n = len(nums)
# sorting a suffix never changes the multiset of the whole array
diff = Counter(nums)
diff.subtract(target)
if any(diff.values()):
return 0
# i can be at most the first index where nums and target differ (the prefix before i is untouched)
max_i = n - 1
for i in range(n):
if nums[i] != target[i]:
max_i = i
break
# target[i..] must be non-increasing, so i is at least the position of the last ascent
min_i = 0
for i in range(n - 1, 0, -1):
if target[i - 1] < target[i]:
min_i = i
break
return max(max_i - min_i + 1, 0)