Quick Overview

Given a string and a list of index pairs whose characters may be swapped any number of times, return the lexicographically smallest string that can be reached. It tests modeling swaps as a graph, finding connected components with union-find or DFS, and reasoning carefully about lexicographic order.

Find the lexicographically smallest string reachable with allowed index swaps

Company: ByteDance

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given a string `s` of lowercase English letters and an array `pairs`, where `pairs[i] = [a, b]` names two 0-indexed positions in `s`. You can swap the characters at the two positions of any pair in `pairs`, any number of times and in any order. Return the lexicographically smallest string that `s` can be changed to after using the swaps. ### Function Signature ```python def smallest_string_with_swaps(s: str, pairs: list[list[int]]) -> str: ``` ### Rules - Each element of `pairs` is a two-element list `[a, b]` of indices into `s`. - Every pair can be used as many times as you like, including zero times, so `s` itself is always reachable. - A pair may appear more than once, and a pair with `a == b` is allowed (swapping a position with itself changes nothing). ### Constraints - `1 <= len(s) <= 10^5` - `0 <= len(pairs) <= 10^5` - `0 <= pairs[i][0], pairs[i][1] < len(s)` - `s` contains only lowercase English letters. ### Examples ```text Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" ``` Positions 0 and 3 can only trade with each other, and so can positions 1 and 2. Swapping 0 and 3 gives "bcad", and swapping 1 and 2 then gives "bacd", which puts the smaller letter of each group first. ```text Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]] Output: "abcd" ``` The pair `[0,2]` joins the two groups, so all four positions are connected and the letters can be fully sorted. ```text Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" ``` No pair links positions 0 and 2 directly, but both link to position 1. Swapping 0 and 1 ("bca"), then 1 and 2 ("bac"), then 0 and 1 again gives "abc".

Overview: Given a string and a list of index pairs whose characters may be swapped any number of times, return the lexicographically smallest string that can be reached. It tests modeling swaps as a graph, finding connected components with union-find or DFS, and reasoning carefully about lexicographic order.

You are given a string `s` made of lowercase English letters and an array `pairs`, where each `pairs[i] = [a, b]` names two 0-indexed positions in `s`. You can swap the characters at the two positions of any pair in `pairs`, as many times as you like and in any order. Return the lexicographically smallest string that `s` can be changed into by using these swaps. Rules: - Each element of `pairs` is a two-element list `[a, b]` of indices into `s`. `pairs` is passed as a single argument: one list of two-element integer lists. - Every pair can be used any number of times, including zero, so `s` itself is always reachable. - A pair may appear more than once, either index may come first, and a pair with `a == b` is allowed (swapping a position with itself changes nothing). - The returned string has the same length as `s`, and the smallest reachable string is unique. - Every index fits in a 32-bit signed integer; no value in this problem exceeds 2^31-1. Example 1: Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" Positions 0 and 3 can only trade with each other, and so can positions 1 and 2. Swapping 0 and 3 gives "bcad", and swapping 1 and 2 then gives "bacd", which puts the smaller letter of each group first. Example 2: Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" No pair links positions 0 and 2 directly, but both link to position 1. Swapping 0 and 1 ("bca"), then 1 and 2 ("bac"), then 0 and 1 again gives "abc". Constraints: - 1 <= len(s) <= 10^5 - 0 <= len(pairs) <= 10^5 - 0 <= pairs[i][0], pairs[i][1] < len(s) - s contains only lowercase English letters.

Constraints

  • 1 <= len(s) <= 10^5
  • 0 <= len(pairs) <= 10^5
  • 0 <= pairs[i][0], pairs[i][1] < len(s)
  • s contains only lowercase English letters.
  • Each pairs[i] is a two-element list of indices; a pair may repeat and a == b is allowed.

Examples

Input: ('a', [])

Expected Output: 'a'

Explanation: Minimum length with no pairs: the single letter comes back unchanged.

Input: ('z', [[0, 0]])

Expected Output: 'z'

Explanation: Minimum length with the self pair [0, 0], which changes nothing.

Hints

  1. Try the example s = "cba" with pairs [[0,1],[1,2]]: positions 0 and 2 share no pair, yet their letters can still trade. What makes that possible?
  2. Group the positions that can ever trade letters with each other, directly or through other positions. What can and cannot change inside one group?
  3. Once you know a group's letters and its positions, decide which letter belongs at the group's leftmost position.

Smallest String From Repeated Index Swaps

mediumByteDanceSoftware Engineer

You are given a string s made of lowercase English letters and an array pairs, where each pairs[i] = [a, b] names two 0-indexed positions in s.

You can swap the characters at the two positions of any pair in pairs, as many times as you like and in any order.

Return the lexicographically smallest string that s can be changed into by using these swaps.

Rules:

  • Each element of pairs is a two-element list [a, b] of indices into s. pairs is passed as a single argument: one list of two-element integer lists.
  • Every pair can be used any number of times, including zero, so s itself is always reachable.
  • A pair may appear more than once, either index may come first, and a pair with a == b is allowed (swapping a position with itself changes nothing).
  • The returned string has the same length as s, and the smallest reachable string is unique.
  • Every index fits in a 32-bit signed integer; no value in this problem exceeds 2^31-1.

Example 1: Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" Positions 0 and 3 can only trade with each other, and so can positions 1 and 2. Swapping 0 and 3 gives "bcad", and swapping 1 and 2 then gives "bacd", which puts the smaller letter of each group first.

Example 2: Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" No pair links positions 0 and 2 directly, but both link to position 1. Swapping 0 and 1 ("bca"), then 1 and 2 ("bac"), then 0 and 1 again gives "abc".

Constraints:

  • 1 <= len(s) <= 10^5
  • 0 <= len(pairs) <= 10^5
  • 0 <= pairs[i][0], pairs[i][1] < len(s)
  • s contains only lowercase English letters.

Examples

Example 1
Input
('a', [])
Output
'a'
Notes
Minimum length with no pairs: the single letter comes back unchanged.
Example 2
Input
('z', [[0, 0]])
Output
'z'
Notes
Minimum length with the self pair [0, 0], which changes nothing.

Constraints

  • •1 <= len(s) <= 10^5
  • •0 <= len(pairs) <= 10^5
  • •0 <= pairs[i][0], pairs[i][1] < len(s)
  • •s contains only lowercase English letters.
  • •Each pairs[i] is a two-element list of indices; a pair may repeat and a == b is allowed.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def smallest_string_with_swaps(s: str, pairs: list[list[int]]) -> str:
Sample call
smallest_string_with_swaps('a', [])
Language
Case 1
Input
('a', [])
Expected
'a'
Case 2
Input
('z', [[0, 0]])
Expected
'z'

Browse More Questions

Show the approach

Approach

Model the indices as nodes of an undirected graph with one edge per pair. Two positions can end up exchanging letters exactly when they lie in the same connected component: swaps along a path move a letter one step at a time, and swaps along the edges of a connected component can produce every permutation of the letters on it. Positions in different components never exchange letters, so each component keeps its own multiset of letters. The reference builds the components with a union-find structure using path compression and union by size. To make the string as small as possible from left to right, each component's letters go into its positions in ascending order: the smallest letter of the component lands on its smallest index, the next smallest on the next index, and so on. Any other arrangement of that component puts a larger letter at the first position where the two strings differ, so it is lexicographically larger, and components do not affect each other. The Python reference sorts each component's letters; the other references count the 26 letters per component and hand out the smallest remaining letter while scanning indices from left to right, which yields the same string. Edge cases: with no pairs every position is its own component and s comes back unchanged; self pairs and repeated pairs merge nothing new; a pair with the larger index first is the same undirected edge; a string of identical letters never changes.

Time complexity:
O(n log n + m α(n)), where n = len(s) and m = len(pairs)
Space complexity:
O(n)