Distribute Elements Into Two Arrays I - Problem
Distribute Elements Into Two Arrays I

You are given a 1-indexed array of distinct integers nums of length n. Your task is to distribute all elements between two dynamic arrays arr1 and arr2 following a specific pattern.

Distribution Rules:
1. First operation: append nums[1] to arr1
2. Second operation: append nums[2] to arr2
3. For the i-th operation (i ≥ 3):
  • If the last element of arr1 > last element of arr2, append nums[i] to arr1
  • Otherwise, append nums[i] to arr2

Goal: Return the result array formed by concatenating arr1 and arr2.

Example: If arr1 = [1,2,3] and arr2 = [4,5,6], then result = [1,2,3,4,5,6]

Input & Output

example_1.py — Basic Distribution
$ Input: nums = [2, 1, 3]
Output: [2, 3, 1]
💡 Note: Step 1: arr1 = [2], arr2 = []. Step 2: arr1 = [2], arr2 = [1]. Step 3: Since 2 > 1, add 3 to arr1. Final: arr1 = [2, 3], arr2 = [1]. Result = [2, 3, 1].
example_2.py — Alternating Pattern
$ Input: nums = [5, 4, 3, 8]
Output: [5, 8, 4, 3]
💡 Note: Step 1: arr1 = [5], arr2 = []. Step 2: arr1 = [5], arr2 = [4]. Step 3: Since 5 > 4, add 3 to arr1, so arr1 = [5, 3]. Step 4: Since 3 < 4, add 8 to arr2, so arr2 = [4, 8]. Result = [5, 3, 4, 8].
example_3.py — Minimum Input
$ Input: nums = [1]
Output: [1]
💡 Note: Only one element, so arr1 = [1], arr2 = []. Result = [1].

Visualization

Tap to expand
Distribution Process VisualizationInput Array: nums = [2, 1, 3, 4]2134arr1:arr2:Step 1: Add nums[0]=2 to arr12Step 2: Add nums[1]=1 to arr221Step 3: 2 > 1, so add nums[2]=3 to arr1231Step 4: 3 > 1, so add nums[3]=4 to arr12341Final Result: [2, 3, 4, 1]2341
Understanding the Visualization
1
Setup
Initialize two empty arrays arr1 and arr2
2
Mandatory Picks
First element goes to arr1, second element goes to arr2
3
Comparison
Compare the last elements of both arrays
4
Decision
Add next element to the array with larger last element
5
Concatenate
Combine arr1 and arr2 to form the final result
Key Takeaway
🎯 Key Insight: This is a straightforward simulation problem - no complex algorithms needed, just follow the rules step by step!

Time & Space Complexity

Time Complexity
⏱️
O(n)

We process each element exactly once, with constant time operations for each

n
2n
Linear Growth
Space Complexity
O(n)

We store all elements in the two arrays plus the result array

n
2n
Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 105
  • All integers in nums are distinct
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen