Relocate Marbles - Problem
Marble Relocation Challenge
Imagine you have a collection of marbles scattered across different positions on a number line. You're given a series of movement instructions that tell you to pick up all marbles from one position and move them to another position.
๐ฏ Your Goal: After executing all movement instructions, return a sorted list of all positions that still contain at least one marble.
Input:
โข
โข
โข
Output: Sorted array of final occupied positions
Note: Multiple marbles can occupy the same position, but we only care about which positions are occupied, not how many marbles are at each position.
Imagine you have a collection of marbles scattered across different positions on a number line. You're given a series of movement instructions that tell you to pick up all marbles from one position and move them to another position.
๐ฏ Your Goal: After executing all movement instructions, return a sorted list of all positions that still contain at least one marble.
Input:
โข
nums - Array of initial marble positionsโข
moveFrom - Array of source positions for each moveโข
moveTo - Array of destination positions for each moveOutput: Sorted array of final occupied positions
Note: Multiple marbles can occupy the same position, but we only care about which positions are occupied, not how many marbles are at each position.
Input & Output
example_1.py โ Basic Movement
$
Input:
nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5]
โบ
Output:
[5,6,8,9]
๐ก Note:
Initial: marbles at [1,6,7,8]. Move 1โ2: [2,6,7,8]. Move 7โ9: [2,6,8,9]. Move 2โ5: [5,6,8,9].
example_2.py โ Multiple Marbles Same Position
$
Input:
nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2]
โบ
Output:
[2]
๐ก Note:
Initial: marbles at [1,1,3,3]. Move all from 1โ2: [2,2,3,3]. Move all from 3โ2: [2,2,2,2]. Only position 2 is occupied.
example_3.py โ No Moves
$
Input:
nums = [1,2,3], moveFrom = [], moveTo = []
โบ
Output:
[1,2,3]
๐ก Note:
No moves to execute, so marbles remain at their initial positions [1,2,3].
Constraints
- 1 โค nums.length โค 105
- 1 โค moveFrom.length, moveTo.length โค 105
- moveFrom.length == moveTo.length
- 1 โค nums[i], moveFrom[i], moveTo[i] โค 109
- Important: moveFrom[i] will always have at least one marble
Visualization
Tap to expand
Understanding the Visualization
1
Initial Occupancy
Rooms 1, 6, 7, and 8 have guests
2
Renovation Notice
Move all guests from room 1 to room 2
3
Another Move
Move all guests from room 7 to room 9
4
Final Move
Move all guests from room 2 to room 5
5
Final Report
Occupied rooms: 5, 6, 8, 9
Key Takeaway
๐ฏ Key Insight: We only need to track which positions are occupied, not how many marbles are at each position. This makes a set the perfect data structure for optimal O(n+m) performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code