#2766

Relocate Marbles

Medium
ArrayHash TableSortingSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m log m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m log m)Space O(n)

In the optimal solution, we can use a set to track the positions of marbles efficiently. Instead of simulating each move, we directly update the set for each move, which allows us to avoid unnecessary iterations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a set to store unique positions of marbles.
  2. 2Step 2: Add all initial positions from nums to the set.
  3. 3Step 3: For each move, remove moveFrom[i] from the set if it exists, and add moveTo[i].
  4. 4Step 4: Convert the set to a sorted list and return it.
solution.py10 lines
1# Full working Python code
2from collections import defaultdict
3
4def relocateMarbles(nums, moveFrom, moveTo):
5    positions = set(nums)
6    for i in range(len(moveFrom)):
7        if moveFrom[i] in positions:
8            positions.remove(moveFrom[i])
9        positions.add(moveTo[i])
10    return sorted(positions)

Complexity note: The time complexity is O(n + m log m), where n is the number of initial positions and m is the number of moves. The set operations (insert and delete) are average O(1), and sorting the final positions takes O(m log m).

  • 1Using a set allows for efficient tracking of unique positions.
  • 2Directly updating positions avoids unnecessary iterations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.