Distribute Elements Into Two Arrays I (LeetCode 3069): Solution and Explanation

Easy
Array
Simulation

Split nums into two arrays: the first element seeds arr1, the second seeds arr2, and each later element joins whichever array currently has the larger last element. Return arr1 followed by arr2. For [2,1,3] the answer is [2,3,1].

Intuition

The rule only ever looks at the last element of each array, so there is nothing to optimize. Following it step by step is the whole solution.

Because the values are distinct, the two tails are never equal and every element has exactly one destination.

Once an element is appended it becomes its array's new tail, which is what the next comparison sees.

Approach: Direct simulation

  1. Start arr1 = [nums[0]] and arr2 = [nums[1]].
  2. For each remaining value x in order, compare arr1[-1] with arr2[-1].
  3. If the tail of arr1 is larger, append x to arr1; otherwise append it to arr2.
  4. Return arr1 + arr2.

Step-by-step example

nums = [2,1,3]
  1. 2 seeds arr1 and 1 seeds arr2.
  2. For 3, the tails are 2 and 1. Since 2 > 1, 3 is appended to arr1, giving arr1 = [2,3].
  3. Concatenate: [2,3] + [1] = [2,3,1].

Code: Python, Java, C++

1class Solution:
2    def resultArray(self, nums: List[int]) -> List[int]:
3        arr1 = [nums[0]]
4        arr2 = [nums[1]]
5        for x in nums[2:]:
6            if arr1[-1] > arr2[-1]:
7                arr1.append(x)
8            else:
9                arr2.append(x)
10        return arr1 + arr2
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element is compared and appended once.

Space

O(n)

The two arrays together hold all n elements.

Other approaches

Fixed-size buffers (time O(n), space O(n))

In languages without growable lists, allocate two arrays of size n with length counters, then copy the second buffer after the first. Same logic, no reallocation.

Common mistakes

  • Comparing the new element with a tail instead of comparing the two tails with each other.
  • Forgetting that the problem is 1-indexed in the statement: the first two operations use the first two elements of the 0-indexed array.
  • Returning arr2 before arr1. The result is always arr1 first.

Frequently asked questions

What if the tails were equal?

It cannot happen here because all values are distinct. The rule would send the element to arr2, since the check is strictly greater.

What does part II change?

Part II decides by counting how many elements in each array are greater than the new value, which needs a sorted structure or a Fenwick tree to stay fast.

Can I build the result in place?

Not easily, since elements interleave between the two arrays. Two buffers and one copy at the end is the simplest correct approach.