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 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. 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
Distribute Elements Into Two Arrays INPUT nums = [2, 1, 3, 3] 2 i=1 1 i=2 3 i=3 3 i=4 Initial Arrays: arr1: [ ] arr2: [ ] Rules: - Op 1: nums[1] goes to arr1 - Op 2: nums[2] goes to arr2 - If last(arr1) > last(arr2): add to arr1, else add to arr2 ALGORITHM STEPS 1 First Operation arr1 = [2], arr2 = [] 2 Second Operation arr1 = [2], arr2 = [1] 3 i=3: Compare 2 vs 1 2 > 1: add 3 to arr1 arr1 = [2,3], arr2 = [1] 4 i=4: Compare 3 vs 1 3 > 1: add 3 to arr1 arr1 = [2,3,3], arr2 = [1] Comparison Summary Op last(a1) last(a2) Result 3 2 1 arr1 4 3 1 arr1 Concatenate: arr1 + arr2 FINAL RESULT Final Arrays: arr1: 2 3 3 arr2: 1 Concatenate result = arr1 + arr2 2 3 3 1 [2, 3, 3, 1] OK Key Insight: The distribution rule compares the LAST elements of arr1 and arr2 at each step. Since 2 > 1 initially, arr1 keeps receiving elements (both 3s). Final result concatenates arr1 + arr2. TutorialsPoint - Distribute Elements Into Two Arrays I | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
425 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