Problem Description
Given an array of initial marble positions and two arrays moveFrom and moveTo representing sequential moves, at each step all marbles at the position moveFrom[i] are moved to moveTo[i]. After performing all moves, return the sorted list of positions that have at least one marble.
Key Insights
- Use a hash map (or dictionary) to count the number of marbles at each position.
- Simulate each move by transferring the count from moveFrom[i] to moveTo[i].
- After processing all moves, the keys of the hash map represent the occupied positions.
- Sorting the keys will give the final sorted list of occupied positions.
Space and Time Complexity
Time Complexity: O(n + m + k log k), where n is the length of nums, m is the number of moves, and k is the number of unique occupied positions. Space Complexity: O(n + m) for the hash map tracking marble counts.
Solution
We initialize a hash map to track the marble count at each position using the initial array nums. For each move defined by moveFrom and moveTo, the marbles at moveFrom[i] are transferred to moveTo[i] by adjusting counts in the map. After processing all moves, the keys of the hash map are the occupied positions, which are then sorted to produce the final result.