Back to December Back to Year 2026
MEDIUM 02 Dec 2026 View on LeetCode

1202. Smallest String With Swaps

</> Solution

/**
 * Problem: LeetCode 1202 - Smallest String With Swaps
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
import java.util.List;

class Solution {
    private int[] parent;

    private int find(int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]]; // path compression
            x = parent[x];
        }
        return x;
    }

    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
        int n = s.length();
        parent = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;

        // Jin indices ko swap kar sakte hain, unhe ek group mein jodo
        for (List<Integer> p : pairs) {
            int a = find(p.get(0));
            int b = find(p.get(1));
            if (a != b) parent[a] = b;
        }

        // Har group (root) ke liye uske characters ka frequency count
        int[][] freq = new int[n][];
        for (int i = 0; i < n; i++) {
            int root = find(i);
            if (freq[root] == null) freq[root] = new int[26];
            freq[root][s.charAt(i) - 'a']++;
        }

        // Har index pe, uske group ka sabse chhota bacha hua character rakho
        int[] ptr = new int[n]; // har root ke liye current smallest char pointer
        char[] res = new char[n];
        for (int i = 0; i < n; i++) {
            int root = find(i);
            int c = ptr[root];
            while (freq[root][c] == 0) c++;
            res[i] = (char) ('a' + c);
            freq[root][c]--;
            ptr[root] = c;
        }

        return new String(res);
    }
}

TIME COMPLEXITY

O((n + m) * alpha(n) + 26 * n)

SPACE COMPLEXITY

O(n + 26 * K) = O(n)

TOPICS

Disjoint Set Line Sweep String Union Find