Count the Number of Good Partitions - 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 the total number of good partitions of nums. Since the answer may be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 8
💡 Note: All elements are unique, so we can partition after any position. With 3 possible split points, we have 2³ = 8 ways: [1,2,3,4], [1][2,3,4], [1,2][3,4], [1,2,3][4], [1][2][3,4], [1][2,3][4], [1,2][3][4], [1][2][3][4]
Example 2 — Repeated Elements
$ Input: nums = [1,2,3,2]
Output: 4
💡 Note: Element 2 appears at positions 1 and 3, so we cannot split between them. Valid partitions: [1,2,3,2], [1][2,3,2], [1,2,3][2], [1][2,3][2]
Example 3 — All Same Elements
$ Input: nums = [1,1,1,1]
Output: 1
💡 Note: Since all elements are the same, we cannot split anywhere. Only one partition possible: [1,1,1,1]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Good Partitions Problem Overview1232index 0index 1index 2index 3Element 2 spans indices 1-3✓ Can split here✗ Cannot split✓ Can split hereValid split points: 2 positionsAnswer: 2² = 4 good partitionsEach element must appear in exactly one subarray
Understanding the Visualization
1
Input Analysis
Array [1,2,3,2] with element 2 appearing at positions 1 and 3
2
Span Calculation
Element 2 spans from index 1 to 3, preventing splits at positions 1 and 2
3
Count Partitions
2 valid split points result in 2² = 4 good partitions
Key Takeaway
🎯 Key Insight: An element's span (first to last occurrence) determines where we can legally partition the array
Asked in
Google 45 Microsoft 32 Amazon 28
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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