#2295
Replace Elements in an Array
MediumArrayHash TableSimulation
Approaches
💡
Intuition
Time Space
In the brute-force approach, we will iterate through the operations and for each operation, we will find the index of the element to replace in the nums array. This is simple but inefficient because we may need to search through the array multiple times.
⚙️
Algorithm
3 steps- 1Step 1: For each operation in operations, find the index of operations[i][0] in nums.
- 2Step 2: Replace nums[index] with operations[i][1].
- 3Step 3: Repeat for all operations.
solution.py7 lines
1# Full working Python code
2nums = [1, 2, 4, 6]
3operations = [[1, 3], [4, 7], [6, 1]]
4for old, new in operations:
5 index = nums.index(old)
6 nums[index] = new
7print(nums)Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.