Count the Number of Good Partitions Problem
Description
LeetCode Problem 2963.
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 10^9 + 7.
Example 1:
Input: nums = [1,2,3,4]
Output: 8
Explanation: The 8 possible good partitions are: ([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]), and ([1,2,3,4]).
Example 2:
Input: nums = [1,1,1,1]
Output: 1
Explanation: The only possible good partition is: ([1,1,1,1]).
Example 3:
Input: nums = [1,2,1,3]
Output: 2
Explanation: The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]).
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Merge Equal Values + Fast Power
Equal numbers must lie in the same subarray, so record the last index of every value. Scan from the left while tracking the furthest last index j seen among the elements so far. When i == j, nothing inside the current block appears later, so a cut is possible here: that closes one minimal block and we count it as k.
With k minimal blocks there are k - 1 gaps between them, and each can be either cut or merged, giving 2^(k - 1) good partitions. Compute this modulo 10^9 + 7 by fast exponentiation.
Complexity: O(n) time and O(n) space for the last-index table.
class Solution:
def numberOfGoodPartitions(self, nums: List[int]) -> int:
last = {x: i for i, x in enumerate(nums)}
mod = 10**9 + 7
j, k = -1, 0
for i, x in enumerate(nums):
j = max(j, last[x])
k += i == j
return pow(2, k - 1, mod)