#3069

Distribute Elements Into Two Arrays I

Easy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach leverages the same logic as the brute force but optimizes the way we handle the arrays by avoiding unnecessary checks and directly using the last elements of the arrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two empty arrays, arr1 and arr2.
  2. 2Step 2: Append the first element of nums to arr1 and the second element to arr2.
  3. 3Step 3: For each subsequent element in nums, directly compare the last elements of arr1 and arr2 to decide where to append the current element.
solution.py10 lines
1def distributeElements(nums):
2    arr1, arr2 = [], []
3    arr1.append(nums[0])
4    arr2.append(nums[1])
5    for i in range(2, len(nums)):
6        if arr1[-1] > arr2[-1]:
7            arr1.append(nums[i])
8        else:
9            arr2.append(nums[i])
10    return arr1 + arr2

Complexity note: The time complexity is O(n) because we only make a single pass through the input array, and the space complexity is O(n) due to the storage of the two result arrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.