LeetCode 915: Partition Array into Disjoint Intervals Solution

Master LeetCode problem 915 (Partition Array into Disjoint Intervals), a medium 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.

915. Partition Array into Disjoint Intervals

Medium

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and keep track of the maximum element seen so far and the maximum element in the left partition. If at any point we encounter an element smaller than the maximum in the left partition, we update the left partition boundary to the current index. At the end of the iteration, the left partition will be the smallest possible partition satisfying the given conditions.

  • Algorithmic Idea:

    1. Iterate through the array while keeping track of the maximum element seen so far and the maximum element in the left partition.
    2. If we encounter an element smaller than the maximum in the left partition, update the left partition boundary.
    3. Return the length of the left partition at the end of the iteration.
  • Time Complexity: O(n) where n is the number of elements in the array.

  • Space Complexity: O(1) as we are not using any extra space other than a few variables.

Solution Code

class Solution {
    public int partitionDisjoint(int[] nums) {
        int leftMax = nums[0];
        int maxInPartition = nums[0];
        int partitionIdx = 0;
        
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < leftMax) {
                partitionIdx = i;
                leftMax = maxInPartition; // update left partition max
            } else {
                maxInPartition = Math.max(maxInPartition, nums[i]);
            }
        }
        
        return partitionIdx + 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 915 (Partition Array into Disjoint Intervals)?

This page provides optimized solutions for LeetCode problem 915 (Partition Array into Disjoint Intervals) 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 915 (Partition Array into Disjoint Intervals)?

The time complexity for LeetCode 915 (Partition Array into Disjoint Intervals) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 915 on DevExCode?

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

Back to LeetCode Solutions