Count Shadow Pairs II Problem
Description
LeetCode Problem 4055.
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[i] < nums[k] < nums[j].
Return the total number of shadow pairs.
Example 1:
Input: nums = [3,1,4,2,5]
Output: 5
Explanation:
(i, j) nums[i] nums[j] Shadow Pair
(0, 2) 3 4 nums[1] = 1 is not strictly between 3 and 4
(1, 2) 1 4 No index k exists such that 1 < k < 2
(1, 3) 1 2 nums[2] = 4 is not strictly between 1 and 2
(2, 4) 4 5 nums[3] = 2 is not strictly between 4 and 5
(3, 4) 2 5 No index k exists such that 3 < k < 4
Thus, the answer is 5.
Example 2:
Input: nums = [6,7,8,9]
Output: 3
Explanation:
(i, j) nums[i] nums[j] Shadow Pair
(0, 1) 6 7 No index k exists such that 0 < k < 1
(1, 2) 7 8 No index k exists such that 1 < k < 2
(2, 3) 8 9 No index k exists such that 2 < k < 3
Thus, the answer is 3.
Constraints:
3 <= n == nums.length <= 5 * 10^41 <= nums[i] <= 10^9
Solution
Approach: Sweep with Segment Tree Beats
Think of each earlier index i as an interval (x, y] on the value axis, where x = nums[i] and y is the smallest value larger than x seen after i so far (infinity at first). A new element w forms a shadow pair with i exactly when x < w <= y: nothing between them lies strictly between the two values.
When w arrives:
- Every interval with
x < wandy > wmust shrink toy = w, becausewis now the smallest larger value afteri. - After this update, the intervals with
y = ware exactly the earlier indices that pair withw. Their count is the number of shadow pairs ending atw. - Add the interval for the new index, with
yset to infinity.
Order the intervals by x (sort the values, one leaf per index). Step 1 is then a "set each value to at most w" update on a prefix of leaves, which a segment tree with maximum, second maximum and count of maxima handles in amortised O(log n): a node whose second maximum is already below w only changes its maximum. Whenever a node lowers its maximum from Y to w, move that node's count of maxima from the bucket cnt[Y] to cnt[w]. Then cnt[w] after the update is the number of pairs ending at w.
Complexity: O(n log n) amortised time (the segment-tree-beats bound) and O(n) extra space.
from bisect import bisect_left
class Solution:
def shadowPairs(self, nums: List[int]) -> int:
n = len(nums)
vals = sorted(set(nums))
m = len(vals)
rank = [bisect_left(vals, v) + 1 for v in nums]
# leaves ordered by value; leaf = first free slot of that value
start = [0] * (m + 2)
for r in rank:
start[r + 1] += 1
for r in range(1, m + 2):
start[r] += start[r - 1]
# start[r] = number of elements with rank < r (= first leaf of rank r)
slot = start[:]
leaf = [0] * n
for i in range(n):
leaf[i] = slot[rank[i]]
slot[rank[i]] += 1
inf = m + 1
size = 1
while size < n:
size *= 2
mx = [0] * (2 * size)
se = [-1] * (2 * size)
cm = [0] * (2 * size)
cnt = [0] * (m + 2)
def pull(o):
a, b = 2 * o, 2 * o + 1
if mx[a] > mx[b]:
mx[o], cm[o] = mx[a], cm[a]
se[o] = max(se[a], mx[b])
elif mx[a] < mx[b]:
mx[o], cm[o] = mx[b], cm[b]
se[o] = max(mx[a], se[b])
else:
mx[o], cm[o] = mx[a], cm[a] + cm[b]
se[o] = max(se[a], se[b])
def push(o):
for c in (2 * o, 2 * o + 1):
if mx[c] > mx[o]:
mx[c] = mx[o]
def chmin(o, l, r, end, w):
# chmin on leaves [0, end)
if l >= end or mx[o] <= w:
return
if r <= end and se[o] < w:
cnt[mx[o]] -= cm[o]
cnt[w] += cm[o]
mx[o] = w
return
push(o)
mid = (l + r) // 2
chmin(2 * o, l, mid, end, w)
chmin(2 * o + 1, mid, r, end, w)
pull(o)
def insert(p):
o, l, r = 1, 0, size
path = []
while r - l > 1:
push(o)
path.append(o)
mid = (l + r) // 2
if p < mid:
o, r = 2 * o, mid
else:
o, l = 2 * o + 1, mid
mx[o], se[o], cm[o] = inf, -1, 1
cnt[inf] += 1
for o in reversed(path):
pull(o)
ans = 0
for i in range(n):
w = rank[i]
chmin(1, 0, size, start[w], w)
ans += cnt[w]
insert(leaf[i])
return ans