Count Shadow Pairs II solution and explanation
The problem
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 * 1041 <= nums[i] <= 109
Approach overview
Problem Overview: Given an array of integers nums and a target integer target, count the number of pairs (i, j) with i < j such that nums[i] + nums[j] == target. This is a classic counting problem that becomes tricky with large inputs and duplicate values.
Approach 1: Brute Force (O(n²) time, O(1) space)
Iterate over every possible pair using two nested loops. For each i, check all j > i and increment the count when the sum matches the target. This is the simplest to implement and works fine for small arrays. It also helps you verify correctness of more efficient solutions. But it's too slow for inputs beyond a few thousand elements—the quadratic time blows up quickly. Use this only if you're writing a quick sanity check or the constraints are tiny.
Approach 2: Sorting + Two Pointers (O(n log n) time, O(1) space)
Sort the array, then place one pointer at the start and another at the end. If the sum of the two pointed elements is greater than the target, move the right pointer left; if it's less, move the left pointer right. Each time the sum equals the target, count the pair and adjust pointers carefully to handle duplicates. For example, if you have multiple equal elements, you need to count all combinations at once by multiplying frequencies. This approach does not require extra space (aside from the sort) and runs in O(n log n) because of sorting. It's a solid fallback if you cannot use a hash map or want to avoid extra memory.
Approach 3: Hash Map (O(n) time, O(n) space)
Traverse the array once. For each element, compute its complement target - nums[i]. Look up the complement in a hash map that stores the frequency of each number seen so far. Add that frequency to the answer, then increment the count of the current number in the map. This counts all ordered pairs exactly once because you only look backward. The key insight is using the map to remember how many previous elements can partner with the current one. It elegantly handles duplicates because the map stores frequency, not just presence. If you instead stored a boolean, you would undercount. This is the expected optimal solution for interviews.
Edge cases and trade-offs: The hash map solution works with negative numbers and duplicates without modification. Two pointers require a sorted array, so you lose the original index order; that's fine if you only need the count. In the hash map version, always update the map after checking the complement so you don't pair an element with itself. For arrays with many identical values, the two-pointer method can count all pairs by multiplying the frequencies of the two matching values, while the hash map naturally accumulates the count during the single pass.
Recommended for interviews: The hash map approach is what interviewers expect. It shows you can identify that only the frequency of previous complements matters, turning an O(n²) brute force into a single pass. The brute force demonstrates basic iteration, but the optimal O(n) with a map demonstrates real problem-solving skill. Make sure to handle duplicates by storing frequency, not just presence. Also mention that the hash map solution is the standard answer for "Count pairs with given sum" and its variations.
For more practice, explore related problems on arrays, hash tables, and two pointers.
The written solution for this problem is still being prepared. Try it yourself in the meantime.
Try solving it yourselfComplexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force | O(n²) | O(1) | Small arrays (n < 1000), sanity checks |
| Sorting + Two Pointers | O(n log n) | O(1) | Memory-constrained, sorted input allowed, duplicates manageable |
| Hash Map | O(n) | O(n) | General case, unsorted large arrays, duplicates |
Frequently asked questions
Count Shadow Pairs II Python solution
Initialize a dictionary to store frequencies and a counter. For each num in nums, add freq.get(target - num, 0) to counter, then increment freq[num]. Return counter after the loop.
How to solve Count Shadow Pairs II in O(n)?
Use a hash map to store the frequency of each number seen so far. For every element, check if the complement (target - current) is in the map and add its frequency to the answer, then increment the current number's frequency.
Can Count Shadow Pairs II be solved with sorting?
Yes. Sort the array and use two pointers from both ends to count pairs. This runs in O(n log n) and uses O(1) extra space, making it a good alternate when memory is constrained.
What is the best approach for Count Shadow Pairs II?
The hash map approach is the best because it solves the problem in O(n) time and O(n) space, handling duplicates naturally. It's the standard optimal solution for counting pairs that sum to a target and works on unsorted arrays.
Is Count Shadow Pairs II asked at Google/Amazon/Meta?
The pattern of counting pairs with a given sum is extremely common in interviews at Google, Amazon, and Meta. This exact problem may not be from a specific company, but solving it thoroughly trains you for similar array and hash map questions.
What data structure is used in Count Shadow Pairs II?
The optimal solution uses a hash map (dictionary in Python, HashMap in Java) to track element frequencies. The two-pointer alternative uses a sorted array with two indices.
What is the time complexity of Count Shadow Pairs II?
The optimal time complexity is O(n) using a hash map. A sorting-based two-pointer approach runs in O(n log n), and brute force is O(n²). Most interviewers expect at least O(n log n), but O(n) is the gold standard.