Distribute Elements Into Two Arrays I - Problem
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
arr1is greater than the last element ofarr2, appendnums[i]toarr1. - Otherwise, append
nums[i]toarr2.
The array result is formed by concatenating the arrays arr1 and arr2. For example, if arr1 == [1,2,3] and arr2 == [4,5,6], then result = [1,2,3,4,5,6].
Return the array result.
Input & Output
Example 1 — Basic Distribution
$
Input:
nums = [2,1,3,3]
›
Output:
[2,3,3,1]
💡 Note:
nums[0]=2 → arr1=[2]. nums[1]=1 → arr2=[1]. nums[2]=3: last(arr1)=2 > last(arr2)=1, so → arr1=[2,3]. nums[3]=3: last(arr1)=3 > last(arr2)=1, so → arr1=[2,3,3]. Result = [2,3,3] + [1] = [2,3,3,1]
Example 2 — Alternating Pattern
$
Input:
nums = [5,4,3,8]
›
Output:
[5,3,4,8]
💡 Note:
nums[0]=5 → arr1=[5]. nums[1]=4 → arr2=[4]. nums[2]=3: last(arr1)=5 > last(arr2)=4, so → arr1=[5,3]. nums[3]=8: last(arr1)=3 < last(arr2)=4, so → arr2=[4,8]. Result = [5,3] + [4,8] = [5,3,4,8]
Example 3 — Minimum Size
$
Input:
nums = [1,2]
›
Output:
[1,2]
💡 Note:
Only two elements: nums[0]=1 → arr1=[1], nums[1]=2 → arr2=[2]. Result = [1] + [2] = [1,2]
Constraints
- 3 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 105
- All elements in nums are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Input
1-indexed array of distinct integers
2
Process
Distribute elements based on last element comparison
3
Output
Concatenated result of arr1 and arr2
Key Takeaway
🎯 Key Insight: Simply simulate the distribution process - compare last elements to decide which array gets the next element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code