LeetCode 1121: Divide Array Into Increasing Sequences Solution

Master LeetCode problem 1121 (Divide Array Into Increasing Sequences), 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.

1121. Divide Array Into Increasing Sequences

Problem Explanation

Explanation:

To solve this problem, we need to divide an array into increasing sequences of length k such that each element in the array belongs to exactly one sequence and the difference between consecutive elements in a sequence is at most 1. We can achieve this by iterating over the array and greedily forming sequences with the help of a hashmap to keep track of the current sequence counts.

  1. Initialize an empty hashmap to store the current counts of each number in the array.
  2. Iterate over the array elements:
    • For each element num, check if num - 1 is present in the hashmap and has a count greater than 0.
      • If true, decrement the count of num - 1 and increment the count of num.
      • If false, check if num + 1 and the next k-1 elements are present in the array and increment their counts. If not, return false.
  3. If we successfully iterate over all elements, return true.

Time Complexity: O(n) Space Complexity: O(n)

: :

Solution Code

class Solution {
    public boolean canDivideIntoSubsequences(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int num : nums) {
            int count = map.getOrDefault(num - 1, 0);
            map.put(num, map.getOrDefault(num, 0) + 1);
            map.put(num - 1, count - 1);
        }
        
        for (int num : nums) {
            if (map.get(num) < 0) {
                return false;
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1121 (Divide Array Into Increasing Sequences)?

This page provides optimized solutions for LeetCode problem 1121 (Divide Array Into Increasing Sequences) 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 1121 (Divide Array Into Increasing Sequences)?

The time complexity for LeetCode 1121 (Divide Array Into Increasing Sequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1121 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1121 in Java, C++, or Python.

Back to LeetCode Solutions