from collections import Counter, defaultdict
class Solution:
def canDivideIntoSubsequences(self, nums, k):
# Find the maximum frequency of any number
freq = Counter(nums)
max_freq = max(freq.values())
# The answer is whether len(nums) >= max_freq * k
return len(nums) >= max_freq * k
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
bool canDivideIntoSubsequences(vector<int>& nums, int k) {
unordered_map<int, int> freq;
int max_freq = 0;
for (int num : nums) {
freq[num]++;
max_freq = max(max_freq, freq[num]);
}
return nums.size() >= max_freq * k;
}
};
import java.util.*;
class Solution {
public boolean canDivideIntoSubsequences(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
int maxFreq = 0;
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
maxFreq = Math.max(maxFreq, freq.get(num));
}
return nums.length >= maxFreq * k;
}
}
var canDivideIntoSubsequences = function(nums, k) {
let freq = {};
let maxFreq = 0;
for (let num of nums) {
freq[num] = (freq[num] || 0) + 1;
maxFreq = Math.max(maxFreq, freq[num]);
}
return nums.length >= maxFreq * k;
};
nums
and an integer k
. Your task is to determine whether it is possible to split nums
into one or more subsequences such that:
nums
is used exactly once (no element is reused).k
elements.True
if it's possible to split nums
as described, or False
otherwise.
nums
is non-decreasing, repeated numbers can't be in the same strictly increasing subsequence.nums
(let's call this frequency max_freq
) determines the minimum number of subsequences we must create — each occurrence must go into a different subsequence to maintain strictly increasing order.k
elements, so we need at least max_freq * k
elements in total to satisfy all subsequences.nums
at least max_freq * k
? If yes, it's possible; if not, it's impossible.
nums
. This helps us find max_freq
, the maximum frequency of any number.k
elements, we must have at least max_freq * k
elements in total.nums
is greater than or equal to max_freq * k
, return True
; otherwise, return False
.We use a hash map (dictionary) for counting because it offers fast, O(1) lookups and updates, making our solution efficient even for large arrays.
Suppose nums = [1,2,2,3,3,4,4,5]
and k = 3
.
max_freq = 2
.
2 * 3 = 6
.len(nums) = 8
is at least 6. It is, so the answer is True
.nums
, since we only need one pass to count frequencies.nums
determines the minimum number of subsequences needed, and each must have at least k
elements. By checking if the array is large enough to accommodate max_freq
subsequences of length k
, we can solve the problem efficiently. This approach avoids brute-force and leverages counting for a clean, O(n) solution.