Leetcode 2295: Replace Elements in an Array

grid47
grid47
Exploring patterns and algorithms
Mar 22, 2024 6 min read

You are given a list of distinct positive integers, nums, and a list of operations. Each operation consists of two elements: operations[i][0] and operations[i][1]. In each operation, you need to replace the element operations[i][0] in nums with the new value operations[i][1]. The number operations[i][1] is guaranteed to not already be in nums. After performing all the operations, return the final array.
Problem
Approach
Steps
Complexity
Input: You are given a list `nums` consisting of distinct integers and a list `operations` with each operation consisting of two integers `operations[i][0]` and `operations[i][1]`.
Example: Input: nums = [10, 20, 30, 40], operations = [[10, 50], [30, 60], [40, 70]]
Constraints:
• 1 <= n, m <= 10^5
• 1 <= nums[i], operations[i][0], operations[i][1] <= 10^6
• All elements in nums are distinct.
Output: Return the modified `nums` after applying all the operations in order.
Example: Output: [50, 20, 60, 70]
Constraints:
Goal: The goal is to replace elements in the list `nums` based on the given operations, while ensuring no duplication occurs during the replacement process.
Steps:
• Step 1: Create a mapping of each number in `nums` to its index.
• Step 2: For each operation, find the index of the element to replace and update it with the new value.
• Step 3: After all operations are performed, return the final array.
Goal: The length of the array `nums` is at most 10^5, and each operation is performed at most 10^5 times.
Steps:
Assumptions:
• The input list `nums` contains distinct integers.
• Each operation replaces an element that exists in `nums` with a new number that does not exist in the list.
Input: Input: nums = [1, 2, 3], operations = [[1, 4], [2, 5], [3, 6]]
Explanation: After the first operation, the list becomes [4, 2, 3]. After the second operation, it becomes [4, 5, 3], and finally, after the third operation, the list becomes [4, 5, 6].

Input: Input: nums = [100, 200, 300], operations = [[100, 500], [200, 600], [300, 700]]
Explanation: The operations replace 100 with 500, 200 with 600, and 300 with 700, resulting in the final array [500, 600, 700].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus