Buddy Strings
Real-world version: One Mandatory Tile ExchangeThe statement here is our own: the same inputs, outputs and technique.
A departure board shows a row of lettered tiles, written as the string s. A technician has to carry out exactly one exchange: pick two different positions i and j of the row and put the tile from position i into position j and the tile from position j into position i. Skipping the exchange is not allowed, and the two positions chosen must be different, although the tiles sitting there may show the same letter.
Given s and the desired row goal, return true if some single exchange turns s into goal, and false otherwise. The two rows are not guaranteed to have the same number of tiles.
Examples
Example 1
- Input
- s = "abcd", goal = "abdc"
- Output
- true
Exchanging positions 2 and 3 of `s` moves c and d past each other and yields "abdc", which is the goal.
Example 2
- Input
- s = "abcd", goal = "abdb"
- Output
- false
The goal asks for a b at position 3, and `s` has no b outside position 1, so no exchange of two positions of `s` can produce it.
Example 3
- Input
- s = "abba", goal = "abba"
- Output
- true
Exchanging positions 1 and 2, which both carry b, leaves the row reading "abba", and that is the goal.
Constraints
- 1 <= s.length, goal.length <= 2 * 10^4
- s and goal consist of lowercase English letters.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def buddy_strings(s: str, goal: str) -> bool:public boolean buddyStrings(String s, String goal)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's