Show problems as
Classic problem #859EasyHash TableString

Buddy Strings

Real-world version: One Mandatory Tile Exchange
Tracked in this browser only
Read Buddy Strings on LeetCode(opens in a new tab)

The 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.

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