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 in nums.
  • operations[i][1] does not exist in nums.

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
Replace Elements in an Array INPUT nums array: 1 2 6 7 8 0 1 2 3 4 operations: [1, 3] Replace 1 with 3 [6, 4] Replace 6 with 4 Initial Hash Map: value --> index 1 --> 0 2 --> 1 6 --> 2 7 --> 3 8 --> 4 ALGORITHM STEPS 1 Build Hash Map Map each value to index 2 Process Op [1,3] Find idx of 1, replace w/ 3 idx = map[1] = 0 nums[0] = 3 map[3] = 0, delete map[1] 3 Process Op [6,4] Find idx of 6, replace w/ 4 idx = map[6] = 2 nums[2] = 4 map[4] = 2, delete map[6] 4 Return Result All operations complete Time: O(n + m) Space: O(n) FINAL RESULT Modified nums array: 3 2 4 7 8 0 1 2 3 4 = Changed Output: [3, 2, 4, 7, 8] OK - All operations applied! Final Hash Map: 3 --> 0 (was 1) 2 --> 1 4 --> 2 (was 6) 7 --> 3 8 --> 4 Key Insight: Hash Map Optimization Using a hash map (value --> index) allows O(1) lookup for each operation instead of O(n) linear search. For each operation [old, new]: find index via map, update array at index, update map (add new, remove old). Total complexity: O(n) to build map + O(m) for operations = O(n + m), much better than O(n * m) brute force. TutorialsPoint - Replace Elements in an Array | Hash Map Optimization
Asked in
Amazon 25 Google 18 Microsoft 15
32.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen