Replace Elements in an Array — LeetCode 2295 Python Solution

MediumArrayHash TableSimulation
Problem
#2295
Pattern
Hash Map
Reading time
2 min

The 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].

Example

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:

Python solution

Python
class Solution:
    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        d = {x: i for i, x in enumerate(nums)}
        for x, y in operations:
            nums[d[x]] = y
            d[y] = d[x]
        return nums

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2295. Replace Elements in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2295. Replace Elements in an Array?
LeetCode 2295. Replace Elements in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2295. Replace Elements in an Array?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2295. Replace Elements in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2295. Replace Elements in an Array cover?
LeetCode 2295. Replace Elements in an Array is tagged Array, Hash Table and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview