Replace Elements in an Array – Java Solution

Language Options

C++ Solution |
Python Solution

Code Solution


class Solution {
  public int[] arrayChange(int[] nums, int[][] operations) {
    Map numToIndex = new HashMap<>();

    for (int i = 0; i < nums.length; ++i)
      numToIndex.put(nums[i], i);

    for (int[] o : operations) {
      final int original = o[0];
      final int replaced = o[1];
      final int index = numToIndex.get(original);
      nums[index] = replaced;
      numToIndex.remove(original);
      numToIndex.put(replaced, index);
    }

    return nums;
  }
}

Problem Description

Imagine you’re at a party, and you want to replace your boring old friend (let's say, the number 5) with a much cooler friend (like the number 10). But wait! You can only swap them if your boring friend is actually at the party. If he’s not, well, tough luck!

In this problem, you’re given an array of integers and a list of operations. Each operation tells you which number to replace and what to replace it with. Your task is to perform all these operations and return the final state of the array.

Approach

The code uses a HashMap to keep track of the indices of the numbers in the array. For each operation, it finds the index of the number to be replaced, updates the array, and adjusts the map accordingly. This way, it efficiently handles the replacements without having to search through the array multiple times.

Time and Space Complexity

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

Real-World Example

Think of it like a game of musical chairs. You have a set number of chairs (the array) and players (the numbers). When the music stops (operations are called), players can swap chairs (replace numbers) only if they’re currently sitting in one. If someone tries to swap a chair that’s empty (a number not in the array), well, they’re just left standing awkwardly in the corner!

Similar Problems

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

  • Two Sum Solution in Java
  • Three Sum Solution in Java
  • Four Sum Solution in Java