Ctrl K

A Chain of Replacements

Medium
You are given an array values of distinct positive integers and a list of replacements swaps. The replacements are applied in order: swaps[i] = [x, y] finds the number x in the array and writes y in its place. It is guaranteed that when each replacement is applied, x is in the array and y is not, so the numbers in the array always stay distinct. Return the array after all replacements have been applied.
Example 1
values=[5, 8, 2], swaps=[[8, 4], [5, 9], [4, 5]] → [9, 5, 2]

8 → 4 gives [5, 4, 2], 5 → 9 gives [9, 4, 2], and 4 → 5 gives [9, 5, 2]. The value 5 had already left the array, so it may come back.

Example 2
values=[3], swaps=[[3, 1], [1, 3]] → [3]

First 3 → 1, then 1 → 3: the array is back where it started.

Example 3
values=[10, 20, 30], swaps=[[20, 7]] → [10, 7, 30]
Constraints
  • 1 ≤ len(values), len(swaps) ≤ 10⁵
  • All numbers in values are distinct
  • len(swaps[i]) == 2
  • 1 ≤ values[i], swaps[i][0], swaps[i][1] ≤ 10⁶
  • Before the i-th replacement, swaps[i][0] is in the array and swaps[i][1] is not
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow Far the Rover Got MediumLast Step With a Lit Run MediumFully Dug Relics MediumRows That Match Columns MediumJobs in Order With Rest Days Medium
loading Python…
Input
values=[5, 8, 2], swaps=[[8, 4], [5, 9], [4, 5]]
Expected
[9, 5, 2]

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.