All problems
0559EasyHash TableString

One Mandatory Tile Exchange

Tracked in this browser only
Write code

Trains the technique from

LeetCode 859Buddy Strings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def buddy_strings(s: str, goal: str) -> bool:
Java
public boolean buddyStrings(String s, String goal)
September 7
Apply