Skip to content

2963. Count the Number of Good Partitions

Description

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.

 

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 <= 105
  • 1 <= nums[i] <= 109

 

Solutions

Solution: Hash Table + Combinatorics

  • Time complexity: O(n)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {number[]} nums
 * @return {number}
 */
const numberOfGoodPartitions = function (nums) {
  const n = nums.length;
  const MODULO = 10 ** 9 + 7;
  const lastMap = new Map();
  let maxRight = 0;
  let result = 1;

  for (let index = 0; index < n; index++) {
    const num = nums[index];

    lastMap.set(num, index);
  }

  for (let index = 0; index < n; index++) {
    const num = nums[index];

    if (index > maxRight) {
      result = (result * 2) % MODULO;
    }

    maxRight = Math.max(lastMap.get(num), maxRight);
  }

  return result;
};

Released under the MIT license