Problem
You are given a 0-indexed integer array nums
representing the initial positions of some marbles. You are also given two 0-indexed integer arrays
moveFrom
and moveTo
of equal length.
Throughout moveFrom.length
steps, you will change the positions of the marbles. On the ith
step, you will move all marbles at position
moveFrom[i]
to position moveTo[i]
.
After completing all the steps, return the sorted list ofoccupied positions.
Notes:
- We call a position occupied if there is at least one marble in that position.
- There may be multiple marbles in a single position.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
1 <= moveFrom.length <= 10^5
moveFrom.length == moveTo.length
1 <= nums[i], moveFrom[i], moveTo[i] <= 10^9
- The test cases are generated such that there is at least a marble in
moveFrom[i]
at the moment we want to apply theith
move.
Solution
Method 1 – Hash Set Simulation
Intuition
We only care about which positions are occupied, not how many marbles are at each position. We can use a set to track all occupied positions, and for each move, remove the source position and add the destination position.
Approach
- Add all initial positions from
nums
to a set. - For each move, if the source position is in the set, remove it and add the destination position.
- At the end, return the sorted list of positions in the set.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m + k log k)
, where n = len(nums), m = len(moveFrom), k = number of unique occupied positions at the end. Each move and set operation is O(1) on average, and sorting the final set is O(k log k). - 🧺 Space complexity:
O(k)
, for the set of occupied positions.