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:
โ€ข nums - Array of initial marble positions
โ€ข moveFrom - Array of source positions for each move
โ€ข moveTo - Array of destination positions for each move

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.

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
Hotel Room ManagementGrand Algorithm HotelRoom1Room2Room6Room7Room8Occupied RoomEmpty RoomMove 1โ†’2Key Insight: Track room occupancy, not individual guests!
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.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 22
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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