Practice problem · easy
A build system runs a pipeline twice, in two environments. Each step ends with a one-letter status code, so a run is a string such as egg.
You want to know whether the two runs follow the same pattern. Steps that share a status in one run must share a status in the other. Steps with different statuses must differ in both. The letters themselves may differ.
Write are_isomorphic(a, b).
a and b are the status strings of the two runs. They have the same length.a with one letter so that you get b. Every occurrence of a letter must become the same letter, and two different letters of a must become different letters.true when the runs follow the same pattern, and false otherwise.Input: a = "egg", b = "add"
Output: trueThe trace reads both strings together and keeps two maps: from a letter of a to a letter of b, and back.
| i | x (from a) | y (from b) | a to b | b to a | Consistent? |
|---|---|---|---|---|---|
| 0 | e | a | e: a | a: e | yes |
| 1 | g | d | e: a, g: d | a: e, d: g | yes |
| 2 | g | d | same | same | yes: g still maps to d |
No conflict appears, so the output is true.
Input: a = "foo", b = "bar"
Output: falseThe letter f would map to b, then the letter o to a and again to r. The two os map to different letters, so the output is false.
Input: a = "ab", b = "aa"
Output: falseThe letters a and b would both map to a. Two different letters cannot share a target, so the output is false.
1 ≤ a.length ≤ 100,000, and b has the same lengtha to z.Comparing every pair of positions costs about n × n / 2 steps, which is 5 × 10^9. Two maps cost one step per position. Each map holds at most 26 letters, so the space is constant.
are_isomorphic · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.