#2295
Medium Algorithms Replace elements in an array
Array Hash Table Simulation
59.6% acceptance
Feb 25, 2026
680
39
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn array_change(mut nums: Vec<i32>, operations: Vec<Vec<i32>>) -> Vec<i32> {
let mut index_map: HashMap<i32, usize> = HashMap::new();
for (i, &v) in nums.iter().enumerate() {
index_map.insert(v, i);
}
for op in &operations {
let (from, to) = (op[0], op[1]);
let idx = index_map.remove(&from).unwrap();
nums[idx] = to;
index_map.insert(to, idx);
}
nums
}
}