Skip to content

2295. Replace Elements in an Array 👍

  • Time: $O(n + m)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
    unordered_map<int, int> numToIndex;

    for (int i = 0; i < nums.size(); ++i)
      numToIndex[nums[i]] = i;

    for (const vector<int>& o : operations) {
      const int original = o[0];
      const int replaced = o[1];
      const int index = numToIndex[original];
      nums[index] = replaced;
      numToIndex.erase(original);
      numToIndex[replaced] = index;
    }

    return nums;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] arrayChange(int[] nums, int[][] operations) {
    Map<Integer, Integer> numToIndex = new HashMap<>();

    for (int i = 0; i < nums.length; ++i)
      numToIndex.put(nums[i], i);

    for (int[] o : operations) {
      final int original = o[0];
      final int replaced = o[1];
      final int index = numToIndex.get(original);
      nums[index] = replaced;
      numToIndex.remove(original);
      numToIndex.put(replaced, index);
    }

    return nums;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def arrayChange(
      self,
      nums: list[int],
      operations: list[list[int]],
  ) -> list[int]:
    numToIndex = {num: i for i, num in enumerate(nums)}

    for original, replaced in operations:
      index = numToIndex[original]
      nums[index] = replaced
      del numToIndex[original]
      numToIndex[replaced] = index

    return nums