Replace Elements in an Array

Problem Description

Ah, the classic “Replace Elements in an Array” problem! It’s like that time you decided to clean your room and ended up just shoving everything into the closet. You know, the one where you think, “If I can just replace these old, dusty items with shiny new ones, everything will be perfect!” Spoiler alert: it rarely is.

In this LeetCode problem, you are given an array of integers and a list of operations. Each operation tells you to replace a specific integer in the array with another integer. It’s like playing a game of musical chairs, but instead of chairs, you have numbers, and instead of music, you have a list of replacements.

Code Solution


class Solution:
    def arrayChange(
        self,
        nums: list[int],
        operations: list[list[int]],
    ) -> list[int]:
        numToIndex = {num: i for i, num in enumerate(nums)}

        for original, replaced in operations:
            index = numToIndex[original]
            nums[index] = replaced
            del numToIndex[original]
            numToIndex[replaced] = index

        return nums

Approach

The approach here is as straightforward as a Sunday morning. We create a mapping of numbers to their indices using a dictionary. Then, for each operation, we find the index of the original number, replace it with the new number, and update our mapping. It’s like keeping a list of your friends’ names and their favorite snacks, and every time someone changes their snack preference, you just update your list. Easy peasy!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n + m)
Space Complexity O(n)

Real-World Example

Imagine you’re at a party, and you have a list of guests (the array). Now, let’s say one of your friends decides to change their outfit (the operations). Instead of kicking them out of the party, you just update your list to reflect their new look. That’s essentially what this problem is asking you to do—keep track of changes without losing your mind (or your guests).

Similar Problems

If you enjoyed this problem, you might also like these: