#2963
Count the Number of Good Partitions
HardArrayHash TableMathCombinatoricsHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a two-pointer technique to efficiently partition the array while ensuring that no two subarrays contain the same number. This reduces the need to check all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Use a HashMap to track the last occurrence of each number.
- 2Step 2: Initialize a variable to count partitions and a pointer to track the end of the last valid partition.
- 3Step 3: Iterate through the array, updating the last occurrence of each number and counting valid partitions based on the last seen index.
solution.py15 lines
1def countGoodPartitions(nums):
2 MOD = 10**9 + 7
3 last_seen = {}
4 count = 1
5 total_partitions = 1
6
7 for i, num in enumerate(nums):
8 if num in last_seen:
9 count = (count * (i - last_seen[num])) % MOD
10 else:
11 count = (count * (i + 1)) % MOD
12 last_seen[num] = i
13 total_partitions = (total_partitions + count) % MOD
14
15 return total_partitionsℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array, and the space complexity is O(n) due to the HashMap storing the last seen indices.
- 1Understanding how to track the last occurrence of elements can significantly reduce complexity.
- 2Using combinatorial counting techniques can help in efficiently calculating the number of valid partitions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.