Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Divide Array Into Increasing Sequences in Python
Suppose we have a non-decreasing array of positive integers called nums and an integer K. We need to determine if this array can be divided into one or more disjoint increasing subsequences, each of length at least K.
For example, if the input is nums = [1,2,2,3,3,4,4] and K = 3, the output will be True because this array can be divided into two subsequences: [1,2,3,4] and [2,3,4], both with lengths at least 3.
Algorithm Approach
The key insight is that we need to find the maximum frequency of any element in the array. If an element appears f times, we need at least f different subsequences to accommodate all occurrences of that element.
To solve this problem, we follow these steps ?
Create a frequency map to count occurrences of each element
Track the maximum frequency encountered
Check if
max_frequency × K ? total_elements
Implementation
def canDivideIntoSubsequences(nums, K):
frequency = {}
max_freq = 0
# Count frequency of each element
for num in nums:
if num not in frequency:
frequency[num] = 1
else:
frequency[num] += 1
# Track maximum frequency
max_freq = max(max_freq, frequency[num])
# Check if division is possible
return max_freq * K <= len(nums)
# Test the function
nums = [1, 2, 2, 3, 3, 4, 4]
K = 3
result = canDivideIntoSubsequences(nums, K)
print(f"Can divide {nums} into subsequences of length {K}: {result}")
Can divide [1, 2, 2, 3, 3, 4, 4] into subsequences of length 3: True
How It Works
In the example [1,2,2,3,3,4,4] with K=3:
Element frequencies: 1 appears 1 time, 2 appears 2 times, 3 appears 2 times, 4 appears 2 times
Maximum frequency is 2 (for elements 2, 3, and 4)
We need at least 2 subsequences, each of length 3
Total elements needed: 2 × 3 = 6
Available elements: 7 ? 6, so division is possible
Alternative Implementation with Collections
from collections import Counter
def canDivideIntoSubsequences(nums, K):
frequency = Counter(nums)
max_freq = max(frequency.values())
return max_freq * K <= len(nums)
# Test with multiple examples
test_cases = [
([1, 2, 2, 3, 3, 4, 4], 3),
([1, 2, 3, 3, 4, 4, 5, 5], 4),
([1, 1, 1, 2, 2, 2], 2)
]
for nums, k in test_cases:
result = canDivideIntoSubsequences(nums, k)
print(f"nums={nums}, K={k}: {result}")
nums=[1, 2, 2, 3, 3, 4, 4], K=3: True nums=[1, 2, 3, 3, 4, 4, 5, 5], K=4: True nums=[1, 1, 1, 2, 2, 2], K=2: False
Time and Space Complexity
Time Complexity: O(n), where n is the length of the array
Space Complexity: O(k), where k is the number of unique elements
Conclusion
The solution works by finding the maximum frequency of any element and checking if we have enough total elements to form the required number of subsequences. This greedy approach efficiently determines if the array division is possible.
