↓Skip to main content
  1. LeetCode/

LeetCode 3069: Distribute Elements Into Two Arrays I

·1 min· ·
LeetCode Easy Array Two-Pointers Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2024-03-03

  • Submissions: Accepted (first try)

Approach
#

Simulate the rule directly (Array Template 5): arr1 = [nums[0]], arr2 = [nums[1]], then each number goes by arr1[-1] > arr2[-1], and the two are joined at the end.

My Solution
#

class Solution:
    def resultArray(self, nums: List[int]) -> List[int]:
        a, b = [nums[0]], [nums[1]]
        for x in nums[2:]:
            (a if a[-1] > b[-1] else b).append(x)
        return a + b

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Compare the arrays’ last elements, not their sums.

Interview Explanation
#

I simulate the rule, appending each number to the array whose last element is larger, and join them at the end. Time O(n).

Related

LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D
LeetCode 682: Baseball Game
·1 min
LeetCode Easy Array Stack Simulation
LeetCode 682 note: keep valid scores on a stack; C removes the last, D adds its double, and + adds the sum of the last two
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 1646: Get Maximum in Generated Array
·2 mins
LeetCode Easy Array Simulation
LeetCode 1646 note: generate by the rules, nums[i // 2] at even i and nums[i // 2] + nums[i // 2 + 1] at odd i, handling n = 0 separately
LeetCode 1089: Duplicate Zeros
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 1089 note: count the zeros to know each value’s shift, then move from back to front, writing the extra 0 when copying a zero