Replace Elements in an Array - Problem
You are given a 0-indexed array nums consisting of n distinct positive integers. Your task is to perform a series of replacement operations that will transform this array step by step.
You need to apply m operations to this array, where each operation is defined by a pair [oldValue, newValue]. In the i-th operation, you must:
- Find the element
operations[i][0]in the array - Replace it with
operations[i][1]
Important guarantees:
- π―
operations[i][0]always exists in the current array - π―
operations[i][1]never exists in the current array before replacement
Return the final array after applying all operations in sequence.
Example: If nums = [1,2,4,6] and operations = [[1,3],[4,7],[6,1]]:
β’ Replace 1 β 3: [3,2,4,6]
β’ Replace 4 β 7: [3,2,7,6]
β’ Replace 6 β 1: [3,2,7,1]
Input & Output
example_1.py β Basic Replacement
$
Input:
nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
βΊ
Output:
[3,2,7,1]
π‘ Note:
Step by step: [1,2,4,6] β replace 1 with 3 β [3,2,4,6] β replace 4 with 7 β [3,2,7,6] β replace 6 with 1 β [3,2,7,1]
example_2.py β Chain Replacements
$
Input:
nums = [1,2], operations = [[1,3],[2,1],[3,2]]
βΊ
Output:
[2,1]
π‘ Note:
Operations create a cycle: [1,2] β [3,2] β [3,1] β [2,1]. Notice how values can be reused after being replaced.
example_3.py β Single Element
$
Input:
nums = [5], operations = [[5,10]]
βΊ
Output:
[10]
π‘ Note:
Edge case with single element: simply replace 5 with 10.
Constraints
- 1 β€ nums.length β€ 105
- 1 β€ nums[i], operations[i][1] β€ 106
- 0 β€ operations.length β€ 105
- operations[i].length == 2
- All values in nums are distinct
- operations[i][0] exists in nums before operation i
- operations[i][1] does not exist in nums before operation i
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Start with books [1,2,4,6] on shelves 0,1,2,3. Create catalog: {1βshelf0, 2βshelf1, 4βshelf2, 6βshelf3}
2
First Replacement
Replace book 1 with book 3: Look up book 1 in catalog (shelf 0), swap it with book 3, update catalog
3
Continue Efficiently
Each subsequent replacement uses the catalog for instant lookup instead of searching every shelf
4
Final Result
After all replacements: [3,2,7,1] with updated catalog maintaining accuracy
Key Takeaway
π― Key Insight: By maintaining a catalog (hash map) of book locations, we transform expensive shelf-by-shelf searches into instant lookups, making the library management system highly efficient for multiple book replacements!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code