#2766
Medium Algorithms Relocate marbles
Array Hash Table Sorting Simulation
51.3% acceptance
Feb 25, 2026
212
19
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 of occupied 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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn relocate_marbles(nums: Vec<i32>, move_from: Vec<i32>, move_to: Vec<i32>) -> Vec<i32> {
use std::collections::HashSet;
let mut pos: HashSet<i32> = nums.into_iter().collect();
for (f, t) in move_from.into_iter().zip(move_to.into_iter()) {
if f != t {
pos.remove(&f);
pos.insert(t);
}
}
let mut result: Vec<i32> = pos.into_iter().collect();
result.sort_unstable();
result
}
}