Divide Array Into Increasing Sequences

Can we partition a sorted array into ≥k-length strictly increasing subsequences? Max frequency check.

Hard
Time O(N) Space O(1)
LeetCode
3 min read
hash-map counting greedy

Problem#

Given a non-decreasing integer array nums and integer k, determine whether nums can be partitioned into one or more strictly increasing subsequences each of length at least k.

Examples#

  • nums = [1,2,2,3,3,4,4], k = 3true (e.g., [1,2,3,4] and [2,3,4]).
  • nums = [5,6,6,7,8], k = 3false.

Constraints#

  • 1 <= nums.length <= 10^5, nums sorted, 1 <= k <= nums.length.

Hints#

Hint
The number of subsequences needed equals the maximum frequency of any value. Check maxFreq * k <= n.

Approach#

Since the array is sorted, equal elements must go into distinct subsequences (each subsequence is strictly increasing). So the number of subsequences needed is at least maxFreq. Each subsequence has length at least k, so we need maxFreq * k <= n.

Solution#

Divide Array Into Increasing Sequences
class Solution {
public:
bool canDivideIntoSubsequences(vector<int>& nums, int k) {
int n = nums.size();
int maxFreq = 1, cur = 1;
for (int i = 1; i < n; ++i) {
cur = (nums[i] == nums[i - 1]) ? cur + 1 : 1;
maxFreq = max(maxFreq, cur);
}
return static_cast<long long>(maxFreq) * k <= n;
}
};

Editorial#

Each occurrence of the most-frequent value must seed its own subsequence (no two equal values can sit in the same strictly increasing chain). With sortedness, runs of equal values are contiguous, so maxFreq is a one-pass scan. Sufficiency: given maxFreq chains and n elements, distributing them round-robin produces chains of length at least floor(n / maxFreq) >= k.

Complexity#

  • Time: O(N).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.