Smallest String With Swaps

You are given a string `s` and an array `pairs` where `pairs[i] = [a, b]` lets you swap the characters at indices `a` and `b`. You may use any pair any number of times. Return the lexicographically smallest string `s` can be turned into.

30:00

Smallest String With Swaps
medium
Free written solution
Topics
Companies

You are given a string s and an array pairs where pairs[i] = [a, b] lets you swap the characters at indices a and b. You may use any pair any number of times. Return the lexicographically smallest string s can be turned into.

Example 1:
Input: {"s":"dcab","pairs":[[0,3],[1,2]]}
Output: bacd
Constraints:
  • 1≤s.length≤1051 \leq s.length \leq 10^5

  • 0≤pairs.length≤1050 \leq pairs.length \leq 10^5

  • 0≤pairs[i][0],pairs[i][1]<s.length0 \leq pairs[i][0], pairs[i][1] < s.length

  • s contains only lowercase English letters

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"dcab","pairs":[[0,3],[1,2]]}
d0c1a2b3arcs = swap pairs
pairs 2

Every index starts as its own group. Any two indices linked by a chain of pairs can trade letters freely, so we join them with union-find.

Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/6