Count the Number of Good Partitions — LeetCode 2963 Python Solution

HardArrayHash TableMathCombinatorics
Problem
#2963
Reading time
2 min

The 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.

Example

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]).

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2963. Count the Number of Good Partitions is filed here because LeetCode tags it Math and Combinatorics, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2963. Count the Number of Good Partitions?
LeetCode 2963. Count the Number of Good Partitions is rated Hard on LeetCode.
What is the time complexity of LeetCode 2963. Count the Number of Good Partitions?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2963. Count the Number of Good Partitions?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2963. Count the Number of Good Partitions cover?
LeetCode 2963. Count the Number of Good Partitions is tagged Array, Hash Table, Math and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview