LeetCode 2963: Count the Number of Good Partitions Solution
Master LeetCode problem 2963 (Count the Number of Good Partitions), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2963. Count the Number of Good Partitions
Problem Explanation
Explanation
To solve this problem, we can iterate through the array from left to right and keep track of the last index where each number occurred. We can use a hashmap to store this information. Then, for each index in the array, we can calculate the number of good partitions that end at that index by considering all possible partitions that end with the current number. Finally, we sum up the total number of good partitions over all indices.
Algorithm:
- Initialize a hashmap to store the last index of each number.
- Initialize a variable to keep track of the total number of good partitions.
- Iterate through the array from left to right.
- For each index, calculate the number of good partitions that end at that index by considering all possible partitions that end with the current number.
- Update the total number of good partitions.
- Return the total number of good partitions modulo 10^9 + 7.
Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n), for the hashmap to store the last index of each number.
Solution Code
class Solution {
public int countGoodPartitions(int[] nums) {
long mod = 1000000007;
Map<Integer, Integer> lastIndices = new HashMap<>();
long goodPartitions = 0;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int lastIndex = lastIndices.getOrDefault(num, -1);
int partitions = i - lastIndex;
goodPartitions += partitions;
lastIndices.put(num, i);
}
return (int)(goodPartitions % mod);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2963 (Count the Number of Good Partitions)?
This page provides optimized solutions for LeetCode problem 2963 (Count the Number of Good Partitions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2963 (Count the Number of Good Partitions)?
The time complexity for LeetCode 2963 (Count the Number of Good Partitions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2963 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2963 in Java, C++, or Python.