Match Two Strings with Exactly One Distinct-Index Swap

Quick Overview

Match Two Strings with Exactly One Distinct-Index Swap. Return whether swapping the characters at exactly two different indices of s can make it equal to goal.

Match Two Strings with Exactly One Distinct-Index Swap

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return whether swapping the characters at exactly two different indices of s can make it equal to goal. Even when the strings already match, a real distinct-index swap is required. ```cpp class Solution { public: bool buddyStrings(string s, string goal); }; ``` ### Examples **Example 1:** ```text s = "abcd", goal = "adcb" Output: true Explanation: Swap positions1 and3. ``` **Example 2:** ```text s = "abc", goal = "abc" Output: false Explanation: Every distinct-index swap changes this string because its letters are unique. ``` ### Constraints - Both string lengths lie in [1,20000]. - All characters are lowercase English letters. ### Contract considerations Use exactly one swap of distinct positions, not zero swaps. ```hint Read the boundary condition What mismatches can one swap change? ``` ### Boundary reminders Use exactly one swap of distinct positions, not zero swaps.

Overview: Match Two Strings with Exactly One Distinct-Index Swap. Return whether swapping the characters at exactly two different indices of s can make it equal to goal.

Amazon logo
Amazon
Jun 26, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return whether swapping the characters at exactly two different indices of s can make it equal to goal. Even when the strings already match, a real distinct-index swap is required.

class Solution {
public:
    bool buddyStrings(string s, string goal);
};

Examples

Example 1:

s = "abcd", goal = "adcb"
Output: true
Explanation: Swap positions1 and3.

Example 2:

s = "abc", goal = "abc"
Output: false
Explanation: Every distinct-index swap changes this string because its letters are unique.

Constraints

  • Both string lengths lie in [1,20000].
  • All characters are lowercase English letters.

Contract considerations

Use exactly one swap of distinct positions, not zero swaps.

Boundary reminders

Use exactly one swap of distinct positions, not zero swaps.