Problem
You are given a 0-indexed array nums
consisting of positive integers.
A partition of an array into one or more contiguous subarrays is called good if no two subarrays contain the same number.
Return _thetotal number of good partitions of _nums
.
Since the answer may be large, return it modulo 10^9 + 7
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Solution
Method 1 – Greedy + Combinatorics (Counting Partition Points)
Intuition
A partition is good if no two subarrays contain the same number. This means that for every number, all its occurrences must be in the same subarray. We can find the last occurrence of each number, and a partition point is valid if all numbers to the left have their last occurrence before or at that point. The answer is the number of ways to choose partition points, which is 2^k
where k
is the number of valid partition points.
Approach
- For each number, record its last occurrence in the array.
- Iterate through the array, keeping track of the farthest last occurrence seen so far.
- If the current index equals the farthest last occurrence, it is a valid partition point.
- The number of good partitions is
2^k
, wherek
is the number of valid partition points (excluding the end of the array). - Return the answer modulo
10^9 + 7
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of nums, since we scan the array twice. - 🧺 Space complexity:
O(n)
, for the hash map of last occurrences.