LeetCode 3069: Distribute Elements Into Two Arrays I Solution

Master LeetCode problem 3069 (Distribute Elements Into Two Arrays I), a easy 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.

3069. Distribute Elements Into Two Arrays I

Problem Explanation

Explanation

To solve this problem, we can iterate through the given array nums and distribute the elements into two arrays arr1 and arr2 based on the condition provided. We will keep track of the last elements of arr1 and arr2 and append the current element to the array with the smaller last element. After distributing all elements, we concatenate arr1 and arr2 to form the final result array.

Algorithm:

  1. Initialize two arrays arr1 and arr2.
  2. Iterate through the elements of nums.
  3. Append the first element of nums to arr1.
  4. For each subsequent element, compare the last elements of arr1 and arr2.
  5. Append the current element to the array with the smaller last element.
  6. Concatenate arr1 and arr2 to get the result array.

Time complexity: O(n) where n is the number of elements in nums. Space complexity: O(n) for the two arrays arr1 and arr2.

Solution Code

class Solution {
    public int[] distributeElements(int[] nums) {
        int[] arr1 = new int[nums.length];
        int[] arr2 = new int[nums.length];
        
        arr1[0] = nums[0];
        int idx1 = 1, idx2 = 0;
        
        for (int i = 1; i < nums.length; i++) {
            if (arr1[idx1 - 1] > arr2[idx2]) {
                arr2[idx2++] = nums[i];
            } else {
                arr1[idx1++] = nums[i];
            }
        }
        
        int[] result = new int[nums.length];
        System.arraycopy(arr1, 0, result, 0, idx1);
        System.arraycopy(arr2, 0, result, idx1, idx2);
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3069 (Distribute Elements Into Two Arrays I)?

This page provides optimized solutions for LeetCode problem 3069 (Distribute Elements Into Two Arrays I) 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 3069 (Distribute Elements Into Two Arrays I)?

The time complexity for LeetCode 3069 (Distribute Elements Into Two Arrays I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3069 on DevExCode?

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

Back to LeetCode Solutions