Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Each operation identifies a value, not an index. Searching the whole array for that value would work, but repeating that search for up to m operations can revisit the same positions many times. The useful fact is that every value is distinct, so each value has exactly one current position that can be stored directly.
Build a map from each current value to its index. For an operation old -> new, read old's position, write new into that array slot, then move the map entry from old to new. The map must describe the array after every operation, because a later operation may refer to a value that was introduced earlier.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n + m) expected | Building the map processes each of the n initial values once. Each of the m operations performs a constant number of expected constant-time hash-table actions and one array write, so no operation scans the array. With adversarial hash collisions, a hash-table action can degrade to O(n), making the worst-case time O(nm). |
| Space | O(n) extra | The map contains one entry per current array value, and the temporary operation references use constant additional space. The returned nums array is required output and is excluded. The extra space remains O(n) for every input arrangement because replacements preserve the number of array elements. |
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
unordered_map<int, int> index;
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
index[nums[i]] = i;
}
for (const vector<int>& operation : operations) {
int oldValue = operation[0];
int newValue = operation[1];
int position = index[oldValue];
nums[position] = newValue;
index[newValue] = position;
index.erase(oldValue);
}
return nums;
}
};The three update lines are one indivisible operation. The array changes first, the new value receives the old value's position, and the old value is removed. Updating only the array makes the current result look correct but leaves later lookups stale; updating only the map creates a map that no longer describes nums.