Ctrl K

Interchangeable Letters

Medium
You are given two strings left and right of equal length. For every position i, the letters left[i] and right[i] are *interchangeable*. Interchangeability carries through chains: if a can be swapped for b and b for c, then a can be swapped for c too. Every letter is interchangeable with itself. You are also given a word word. Each of its letters may independently be replaced by any letter interchangeable with it. Return the lexicographically smallest word you can get this way.
Example 1
left="tab", right="kxy", word="bat" → 'bak'

The pairs form groups {t, k}, {a, x} and {b, y}. b stays b, a stays a, and t becomes k, giving bak.

Example 2
left="cd", right="dz", word="zoo" → 'coo'

c = d and d = z, so c, d and z are interchangeable. z turns into c, and o has no pairs: coo.

Example 3
left="m", right="m", word="mmm" → 'mmm'
Constraints
  • 1 ≤ len(left) = len(right) ≤ 1000
  • 1 ≤ len(word) ≤ 1000
  • All strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRatio Chain Queries MediumMerge Contact Cards MediumChains of Synonyms MediumConsistent Letter Equations MediumRearrange Through Links Medium
loading Python…
Input
left="tab", right="kxy", word="bat"
Expected
'bak'

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