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: 2
💡 Note: Element 2 appears at positions 1 and 3, so we cannot split between them. We can only split after position 0. This gives us 2^1 = 2 valid partitions: [1,2,3,2] and [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
Count the Number of Good Partitions INPUT Array nums[] 1 i=0 2 i=1 3 i=2 4 i=3 Good Partition Rule: No two subarrays can contain the same number All elements distinct! Last Occurrence: 1-->0, 2-->1, 3-->2, 4-->3 n = 4 elements All unique values ALGORITHM STEPS 1 Find Last Occurrence Map each value to its rightmost index 2 Count Valid Splits Track max last occurrence seen so far (maxRight) 3 Valid Split Point If maxRight == i, we can split here safely 4 Calculate Result With k split points: result = 2^k mod (10^9+7) For nums = [1,2,3,4]: Valid splits: after 0,1,2 (k=3) 2^3 = 8 partitions (each split: include or not) FINAL RESULT All 8 Good Partitions: [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] OK OK OK OK OK OK OK OK Output: 8 All partitions valid! No repeated values in any Key Insight: When all elements are distinct, each position (except last) is a valid split point. With n-1 possible split points, each can be used or not, giving 2^(n-1) total partitions. For repeated elements, track the last occurrence of each value - a split is only valid when all prior elements' last occurrences are passed. TutorialsPoint - Count the Number of Good Partitions | Combinatorial Analysis Approach
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