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
Library Book Organization AnalogyBook A(ID: 1)Book B(ID: 2)Book C(ID: 3)Book B(ID: 2)Same ID spans positions 1-3Section 1: [A]Section 2: [B,C,B]โœ“ Valid: No book ID appears in multiple sectionsโœ— Invalid: [A,B] [C,B] would have B in both sections
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.
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
43.7K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen