Spent a bit too long second-guessing edge cases.
Maintain a frequency map of values and the current total sum. For each query (old, new), if old == new, skip; otherwise, update the sum by adding (new - old) * frequency[old], then update the frequency map by moving the count from old to new. This yields O(n + q) time.
Pro tip: Clarify edge cases upfront: if old equals new, no change; if old not present, skip. Also mention that using a hash map ensures O(1) per query, which is optimal for large inputs.
Restate the problem: given an array and queries that replace all occurrences of old with new, return the sum after each query. Confirm that queries are applied sequentially and that replacements affect subsequent queries.
Use a hash map to store the frequency of each value in the array. Maintain a running total sum of all elements. This allows O(1) updates per query.
For each query (old, new): if old == new, skip. If old not in map, skip. Otherwise, let count = freq[old]. Update sum += (new - old) * count. Then update freq[new] += count and remove old from map.
After processing each query, append the current sum to the result list. Return the list after all queries.
Time: O(n + q) where n is array length and q is number of queries. Space: O(n) for the frequency map. This is optimal.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.