Relocate Marbles — LeetCode 2766 Python Solution
MediumArrayHash TableSortingSimulation
- Problem
- #2766
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5]
- Output
- [5,6,8,9]
- Explanation
- Initially, the marbles are at positions 1,6,7,8.
Python solution
Python
class Solution:
def relocateMarbles(
self, nums: List[int], moveFrom: List[int], moveTo: List[int]
) -> List[int]:
pos = set(nums)
for f, t in zip(moveFrom, moveTo):
pos.remove(f)
pos.add(t)
return sorted(pos)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2766. Relocate Marbles is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2766. Relocate Marbles?
- LeetCode 2766. Relocate Marbles is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2766. Relocate Marbles?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2766. Relocate Marbles?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2766. Relocate Marbles cover?
- LeetCode 2766. Relocate Marbles is tagged Array, Hash Table, Sorting and Simulation on LeetCode.