Problem Description
You are given a 1-indexed array of distinct integers nums
of length n
. You need to distribute all the elements of nums
between two arrays arr1
and arr2
using n
operations. In the first operation, append nums[1]
to arr1
. In the second operation, append nums[2]
to arr2
. Afterwards, in the i-th
operation, if the last element of arr1
is greater than the last element of arr2
, append nums[i]
to arr1
. Otherwise, append nums[i]
to arr2
. The array result
is formed by concatenating the arrays arr1
and arr2
. Return the array result
.
Key Insights
- The operations alternate between two arrays based on the comparison of their last elements.
- The first two elements are directly assigned to
arr1
andarr2
. - The subsequent elements are placed based on the comparison of the last elements of the two arrays.
- The entire procedure is straightforward and involves a simple iteration over the input array.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution involves simulating the distribution of elements into two arrays. We maintain two lists, arr1
and arr2
, and iterate through the given nums
array. We append the first element to arr1
and the second to arr2
. For subsequent elements, we check the last elements of both arrays to decide where to place the current element. Finally, we concatenate both arrays to form the result.