LeetCode Problem

How to Solve Smallest String With Swaps

To solve the "Smallest String With Swaps" problem, first identify connected components in the string using union-find or DFS. Then, within each component, sort the characters and place them back in the string to form the lexicographically smallest string. The key challenge is recognizing that the problem can be modeled as a graph where indices are connected by swaps.

GhostInterview Help

Need help with Smallest String With Swaps without spending extra time grinding it?

GhostInterview can read Smallest String With Swaps from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #1202Array scanning plus hash lookupReviewed 2026-03-07
Difficulty
Medium
Primary pattern
Array scanning plus hash lookup
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve the "Smallest String With Swaps" problem, first identify connected components in the string using union-find or DFS. Then, within each component, sort the characters and place them back in the string to form the lexicographically smallest string. The key challenge is recognizing that the problem can be modeled as a graph where indices are connected by swaps.

Problem Statement

You are given a string s, and an array of pairs of indices pairs, where each pair [a, b] indicates that you can swap the characters at indices a and b of the string. Your goal is to return the lexicographically smallest string that can be obtained by repeatedly swapping characters as described.

The indices in pairs can be used any number of times, so it is crucial to find all indices that are connected, either directly or indirectly, through the given pairs. By sorting the characters within each connected component, you can obtain the smallest possible string.

Examples

Example 1

Input: s = "dcab", pairs = [[0,3],[1,2]]

Output: "bacd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[1] and s[2], s = "bacd"

Example details omitted.

Example 2

Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]

Output: "abcd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[0] and s[2], s = "acbd" Swap s[1] and s[2], s = "abcd"

Example details omitted.

Example 3

Input: s = "cba", pairs = [[0,1],[1,2]]

Output: "abc" Explaination: Swap s[0] and s[1], s = "bca" Swap s[1] and s[2], s = "bac" Swap s[0] and s[1], s = "abc"

Example details omitted.

Constraints

  • 1 <= s.length <= 10^5
  • 0 <= pairs.length <= 10^5
  • 0 <= pairs[i][0], pairs[i][1] < s.length
  • s only contains lower case English letters.

Solution Approach

Union-Find Approach

Use a union-find data structure to group indices that are connected through the given swap pairs. Once the groups (connected components) are identified, for each group, sort the characters and assign them back to the string to get the lexicographically smallest result.

Depth-First Search (DFS) Approach

Treat the string indices as nodes in a graph and each pair in pairs as an undirected edge. Use DFS to explore all nodes in the same connected component. After finding all connected indices, sort the characters in those positions and place them back in the string to achieve the smallest string.

Breadth-First Search (BFS) Approach

Alternatively, use BFS to explore connected components, starting from each unvisited node. Once the connected component is found, sort the corresponding characters and reconstruct the string with the sorted characters.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

The time complexity depends on the approach used. For union-find, the time complexity is O(N * α(N)) where N is the length of the string, and α is the inverse Ackermann function. Sorting each connected component contributes an additional O(K log K), where K is the size of the component. For DFS/BFS, the complexity is O(N + M) where N is the number of nodes (characters) and M is the number of edges (pairs). The space complexity is O(N) due to the data structures used for the union-find or graph representation.

What Interviewers Usually Probe

  • Look for understanding of graph theory, particularly connected components.
  • Pay attention to how the candidate handles sorting within each connected component.
  • Check for optimization in the approach, especially in handling large inputs.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to sort the characters within each connected component.
  • Failing to recognize that the problem is essentially about identifying connected components in a graph.
  • Not handling edge cases like no pairs or the minimum string length.

Follow-up variants

  • What if the swaps are limited to certain indices?
  • How would you optimize this problem for larger strings or more pairs?
  • Can this problem be solved with dynamic programming instead of graph traversal?

How GhostInterview Helps

  • GhostInterview breaks down this problem by showing how graph theory can simplify the solution, making it easier to identify connected components.
  • It offers a variety of approaches, from union-find to DFS/BFS, helping you choose the most efficient solution for the given constraints.
  • By highlighting common pitfalls, GhostInterview ensures you're prepared to avoid the usual mistakes and focus on optimizing your solution.

Topic Pages

FAQ

What is the main algorithm used in Smallest String With Swaps?

The problem can be solved using union-find, DFS, or BFS to identify connected components and then sorting the characters within each component.

How do swaps in Smallest String With Swaps help minimize the string?

By swapping characters that are part of the same connected component, you can sort them lexicographically to obtain the smallest possible string.

What is the time complexity of the solution for Smallest String With Swaps?

The time complexity is O(N * α(N)) for union-find, or O(N + M) for DFS/BFS, where N is the number of characters and M is the number of pairs.

Can Smallest String With Swaps be solved without sorting?

No, sorting is essential to ensure the characters within each connected component are arranged lexicographically.

What is the graph theory application in Smallest String With Swaps?

The problem can be viewed as a graph where indices are nodes, and pairs are edges. The goal is to find connected components and sort the characters within them.

GhostInterview Solver

Need direct help with Smallest String With Swaps instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Smallest String With Swaps from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.