Count Shadow Pairs I Problem
Description
LeetCode Problem 4054.
You are given an integer array nums of length n.
A pair of indices (i, j) is called a shadow pair if all of the following conditions are satisfied:
0 <= i < j < nnums[i] < nums[j]- There does not exist an index
ksuch thati < k < jandnums[k] < nums[i] < nums[j].
Return the total number of shadow pairs.
Example 1:
Input: nums = [3,1,4,1,5]
Output: 3
Explanation:
(i, j) nums[i] nums[j] Shadow Pair
(1, 2) 1 4 No index k exists such that 1 < k < 2
(1, 4) 1 5 nums[2] = 4 and nums[3] = 1 are not smaller than 1
(3, 4) 1 5 No index k exists such that 3 < k < 4
Thus, the answer is 3.
Example 2:
Input: nums = [6,7,6,6,7]
Output: 4
Explanation:
(i, j) nums[i] nums[j] Shadow Pair
(0, 1) 6 7 No index k exists such that 0 < k < 1
(0, 4) 6 7 nums[1] = 7, nums[2] = 6, and nums[3] = 6 are not smaller than 6
(2, 4) 6 7 nums[3] = 6 is not smaller than 6
(3, 4) 6 7 No index k exists such that 3 < k < 4
Thus, the answer is 4.
Example 3:
Input: nums = [1,2,3,4]
Output: 6
Explanation:
(i, j) nums[i] nums[j] Shadow Pair
(0, 1) 1 2 No index k exists such that 0 < k < 1
(0, 2) 1 3 nums[1] = 2 is not smaller than 1
(0, 3) 1 4 nums[1] = 2 and nums[2] = 3 are not smaller than 1
(1, 2) 2 3 No index k exists such that 1 < k < 2
(1, 3) 2 4 nums[2] = 3 is not smaller than 2
(2, 3) 3 4 No index k exists such that 2 < k < 3
Thus, the answer is 6.
Constraints:
3 <= n == nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Monotonic Stack
For an index i, let end[i] be the first index to its right with a smaller value (or n). A pair (i, j) is a shadow pair exactly when i < j < end[i] and nums[j] > nums[i]: any k in between with a smaller value would be at or after end[i], so every element strictly between i and end[i] is at least nums[i]. The count for i is therefore the number of elements strictly between i and end[i] minus those equal to nums[i].
Go from right to left with a monotonic stack to find nx, the nearest index to the right whose value is <= nums[i]:
- If
nums[nx] < nums[i], thenend[i] = nxand no equal value lies in between. - If
nums[nx] == nums[i], thenend[i] = end[nx]and the equal values are those ofnxplusnxitself:eq[i] = eq[nx] + 1. - If there is no such
nx, thenend[i] = nandeq[i] = 0.
Add end[i] - i - 1 - eq[i] for every i.
Complexity: O(n) time and O(n) space.
class Solution:
def shadowPairs(self, nums: List[int]) -> int:
n = len(nums)
# end[i]: first index after i holding a smaller value (n if none)
# eq[i]: how many values equal to nums[i] lie strictly between i and end[i]
end = [n] * n
eq = [0] * n
stack = []
ans = 0
for i in range(n - 1, -1, -1):
while stack and nums[stack[-1]] > nums[i]:
stack.pop()
if stack:
nx = stack[-1] # nearest index to the right with a value <= nums[i]
if nums[nx] < nums[i]:
end[i] = nx
else:
end[i] = end[nx]
eq[i] = eq[nx] + 1
stack.append(i)
# everything strictly between i and end[i] is >= nums[i]; keep the strictly larger ones
ans += end[i] - i - 1 - eq[i]
return ans