Practice problem · easy
A train booking app lets people look up a booking by its code, which uses capital letters and digits. A common typing slip is to put two characters in the wrong order, such as 9P instead of P9.
Before the app says "not found", it checks whether the typed text becomes a known code after swapping exactly two of its characters. Your team lead asks: "Write that check for one typed text and one code."
Write one_swap_away(typed, code).
typed and swap the characters there.true if some such swap makes typed equal to code, and false if none does.Input: typed = "9PK3X1", code = "P9K3X1"
Output: trueCompare the two texts position by position and list the positions where they differ.
| Position | typed | code | Same? |
|---|---|---|---|
| 0 | 9 | P | no |
| 1 | P | 9 | no |
| 2 | K | K | yes |
| 3 | 3 | 3 | yes |
| 4 | X | X | yes |
| 5 | 1 | 1 | yes |
Exactly two positions differ, 0 and 1. The character typed has at 0 is the one code needs at 1, and the other way round, so swapping them makes the texts equal.
Input: typed = "AB1B2", code = "AB1B2"
Output: trueThe texts are already equal. A swap must still happen, and swapping the two B characters changes nothing.
Input: typed = "AB12", code = "AB12"
Output: falseThe texts are equal, but all four characters are different. Any swap breaks the match.
1 ≤ len(typed), len(code) ≤ 100,000A to Z and the digits 0 to 9.A text can have 100,000 characters, which gives about 5 billion pairs of positions to swap. Each swap and comparison would read the whole text again. Looking at each position once costs 100,000 steps, and the answer needs only the positions that differ.
one_swap_away · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.