Replace elements in an array

December 17, 2022

array-and-hashmap

Problem URL: Replace elements in an array

We will use a hashmap to store the index of the input array for constant time lookup. Then we will iterate through the operations, and for each operation, we will update the value of the input array. We will also update the index of the input array in the hashmap.

class Solution:
    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        lookup = {}
        for i, num in enumerate(nums):
            lookup[num] = i

        for val, replace in operations:
            if val in lookup:
                nums[lookup[val]] = replace
                lookup[replace] = lookup[val]

        return nums

Time complexity: O(n+m)
Space complexity: O(n)