Replace Elements in an Array
MediumUpdated: Aug 2, 2025
Practice on:
Problem
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 innums.operations[i][1]does not exist innums.
Return the array obtained after applying all the operations.
Examples
Example 1
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [_**3**_ ,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,_**7**_ ,6].
- Replace the number 6 with 1. nums becomes [3,2,7,_**1**_].
We return the final array [3,2,7,1].
Example 2
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [_**3**_ ,2].
- Replace the number 2 with 1. nums becomes [3,_**1**_].
- Replace the number 3 with 2. nums becomes [_**2**_ ,1].
We return the array [2,1].
Constraints
n == nums.lengthm == operations.length1 <= n, m <= 10^5- All the values of
numsare distinct. operations[i].length == 21 <= nums[i], operations[i][0], operations[i][1] <= 10^6operations[i][0]will exist innumswhen applying theithoperation.operations[i][1]will not exist innumswhen applying theithoperation.
Solution
Method 1 - Hash Map for Index Tracking
Intuition
To efficiently replace elements in the array, we need to quickly find the index of the number to be replaced. Using a hash map from value to index allows O(1) updates for each operation.
Approach
- Build a hash map from value to index for the initial nums array.
- For each operation [old, new]:
- Find the index of old in nums using the map.
- Replace nums[index] with new.
- Update the map: remove old, add new with the same index.
- Return the modified nums array.
Code
C++
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
unordered_map<int, int> pos;
for (int i = 0; i < nums.size(); ++i) pos[nums[i]] = i;
for (auto& op : operations) {
int idx = pos[op[0]];
nums[idx] = op[1];
pos[op[1]] = idx;
pos.erase(op[0]);
}
return nums;
}
Go
func arrayChange(nums []int, operations [][]int) []int {
pos := make(map[int]int)
for i, v := range nums {
pos[v] = i
}
for _, op := range operations {
idx := pos[op[0]]
nums[idx] = op[1]
pos[op[1]] = idx
delete(pos, op[0])
}
return nums
}
Java
import java.util.*;
public class Solution {
public int[] arrayChange(int[] nums, int[][] operations) {
Map<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < nums.length; i++) pos.put(nums[i], i);
for (int[] op : operations) {
int idx = pos.get(op[0]);
nums[idx] = op[1];
pos.put(op[1], idx);
pos.remove(op[0]);
}
return nums;
}
}
Kotlin
fun arrayChange(nums: IntArray, operations: Array<IntArray>): IntArray {
val pos = mutableMapOf<Int, Int>()
for (i in nums.indices) pos[nums[i]] = i
for (op in operations) {
val idx = pos[op[0]]!!
nums[idx] = op[1]
pos[op[1]] = idx
pos.remove(op[0])
}
return nums
}
Python
def arrayChange(nums, operations):
pos = {v: i for i, v in enumerate(nums)}
for old, new in operations:
idx = pos.pop(old)
nums[idx] = new
pos[new] = idx
return nums
Rust
use std::collections::HashMap;
fn array_change(nums: &mut [i32], operations: &[[i32; 2]]) -> Vec<i32> {
let mut pos: HashMap<i32, usize> = nums.iter().enumerate().map(|(i, &v)| (v, i)).collect();
for op in operations {
let idx = pos.remove(&op[0]).unwrap();
nums[idx] = op[1];
pos.insert(op[1], idx);
}
nums.to_vec()
}
TypeScript
function arrayChange(nums: number[], operations: number[][]): number[] {
const pos = new Map<number, number>();
nums.forEach((v, i) => pos.set(v, i));
for (const [oldVal, newVal] of operations) {
const idx = pos.get(oldVal)!;
nums[idx] = newVal;
pos.set(newVal, idx);
pos.delete(oldVal);
}
return nums;
}
Complexity
- ⏰ Time complexity: O(n + m), where n = nums.length and m = operations.length.
- 🧺 Space complexity: O(n), for the value-to-index map.