Smallest String Reachable Through Allowed Index Swaps
Company: Goldman Sachs
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
### Problem
Each pair gives two zero-based positions whose characters may be swapped any number of times. Return the lexicographically smallest string reachable from s using these allowed swaps.
```cpp
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs);
};
```
### Examples
**Example 1:**
```text
Input: s = "cbad", pairs = [[0,1]]
Output: "bcad"
Explanation: Only positions0 and1 can exchange characters, so their b,c values are sorted there.
```
**Example 2:**
```text
Input: s = "zxy", pairs = [[0,1],[1,2]]
Output: "xyz"
Explanation: The connected chain permits every permutation of the three positions.
```
### Constraints
- s has length 1 to 100000 and uses lowercase English letters.
- There are 0 to 100000 index pairs.
- Both labels in every pair lie in `[0,s.length-1]`.
### Contract considerations
The permitted operations may have many sequences, but their lexicographically minimum string is a unique result.
```hint Read the boundary condition
May an allowed pair be used repeatedly, and what result is required when there are no allowed pairs?
```
### Boundary reminders
The permitted operations may have many sequences, but their lexicographically minimum string is a unique result.
Overview: Smallest String Reachable Through Allowed Index Swaps. Each pair gives two zero-based positions whose characters may be swapped any number of times.
Smallest String Reachable Through Allowed Index Swaps
Goldman Sachs
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0
Problem
Each pair gives two zero-based positions whose characters may be swapped any number of times. Return the lexicographically smallest string reachable from s using these allowed swaps.
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs);
};
Examples
Example 1:
Input: s = "cbad", pairs = [[0,1]]
Output: "bcad"
Explanation: Only positions0 and1 can exchange characters, so their b,c values are sorted there.
Example 2:
Input: s = "zxy", pairs = [[0,1],[1,2]]
Output: "xyz"
Explanation: The connected chain permits every permutation of the three positions.
Constraints
s has length 1 to 100000 and uses lowercase English letters.
There are 0 to 100000 index pairs.
Both labels in every pair lie in
[0,s.length-1]
.
Contract considerations
The permitted operations may have many sequences, but their lexicographically minimum string is a unique result.
Boundary reminders
The permitted operations may have many sequences, but their lexicographically minimum string is a unique result.