Replace Elements in an Array Problem
#2295
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2295.
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the i^th operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the i^th operation:
operations[i][0]exists innums.operations[i][1]does not exist innums.
Return the array obtained after applying all the operations.
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 thei^thoperation.operations[i][1]will not exist innumswhen applying thei^thoperation.
Solution
Approach: Hash Table
Map every value to its index in nums. For an operation [x, y], overwrite the slot at d[x] with y, then record that y now lives at that same index. Return nums at the end.
Complexity: O(n + m) time, O(n) space, where n is the length of nums and m the number of operations.
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