Count the Number of Good Partitions - Problem
You are given a 0-indexed array nums consisting of positive integers. Your task is to find all possible ways to partition this array into contiguous subarrays such that no two subarrays share a common element.
A partition is called "good" if:
- The array is divided into one or more contiguous subarrays
- Each number appears in exactly one subarray
- No two subarrays contain the same number
Example: For array [1,2,3,2], we cannot split after index 1 because both subarrays [1,2] and [3,2] would contain the number 2.
Return the total number of good partitions possible. Since the answer may be large, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,3,2]
โบ
Output:
2
๐ก Note:
The valid partitions are: [1,2,3,2] and [1] [2,3,2]. We cannot partition as [1,2] [3,2] because both subarrays contain the number 2.
example_2.py โ All Unique Elements
$
Input:
nums = [1,2,3]
โบ
Output:
4
๐ก Note:
All possible partitions are valid since all numbers are unique: [1,2,3], [1,2] [3], [1] [2,3], [1] [2] [3].
example_3.py โ Single Element
$
Input:
nums = [5]
โบ
Output:
1
๐ก Note:
There is only one way to partition a single element array: [5].
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- Answer should be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Scan Books
Record the position of each book ID's last occurrence
2
Track Active Range
As we process each position, track the furthest we must go to complete all current book IDs
3
Identify Section Breaks
When current position matches the active range end, we can close this section
4
Count Possibilities
Each valid section break gives us 2 choices: split or continue
Key Takeaway
๐ฏ Key Insight: A partition is only valid when all active book IDs (numbers) have been completely processed, meaning their ranges don't extend beyond the current position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code