Replace Elements in an Array - 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 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.
Input & Output
Example 1 — Basic Replacement
$
Input:
nums = [1,2,6,7,8], operations = [[1,3],[6,4]]
›
Output:
[3,2,4,7,8]
💡 Note:
First operation: replace 1 with 3, array becomes [3,2,6,7,8]. Second operation: replace 6 with 4, final array is [3,2,4,7,8].
Example 2 — Single Operation
$
Input:
nums = [1,2,3], operations = [[2,5]]
›
Output:
[1,5,3]
💡 Note:
Only one operation: replace 2 with 5, so nums[1] changes from 2 to 5.
Example 3 — No Change Elements
$
Input:
nums = [10,20,30,40], operations = [[10,50],[30,60]]
›
Output:
[50,20,60,40]
💡 Note:
Replace 10→50 and 30→60. Elements 20 and 40 remain unchanged as they're not in operations.
Constraints
- 1 ≤ nums.length ≤ 103
- 1 ≤ nums[i] ≤ 106
- 1 ≤ operations.length ≤ 103
- operations[i].length == 2
- 1 ≤ operations[i][0], operations[i][1] ≤ 106
- operations[i][0] exists in nums
- operations[i][1] does not exist in nums
- All values in nums are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Input
nums = [1,2,6,7,8], operations = [[1,3],[6,4]]
2
Process
Apply each operation: replace target elements with new values
3
Output
Result array: [3,2,4,7,8]
Key Takeaway
🎯 Key Insight: Use hash map to precompute all replacements, then apply changes in single pass for optimal efficiency.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code