Leetcode 1202: Smallest String With Swaps

grid47
grid47
Exploring patterns and algorithms
Jul 9, 2024 6 min read

You are given a string s and an array of pairs of indices pairs where each pair pairs[i] = [a, b] represents two indices in the string. You can swap the characters at any of these index pairs any number of times. Your task is to return the lexicographically smallest string that can be obtained after performing the swaps.
Problem
Approach
Steps
Complexity
Input: You are given a string s and a 2D array pairs where each pair represents two indices in the string that can be swapped.
Example: Input: s = "zaxy", pairs = [[0,3],[1,2]]
Constraints:
• 1 <= s.length <= 10^5
• 0 <= pairs.length <= 10^5
• 0 <= pairs[i][0], pairs[i][1] < s.length
• s only contains lowercase English letters.
Output: Return the lexicographically smallest string that can be obtained by swapping the characters at the given pairs of indices.
Example: Output: "axyz"
Constraints:
Goal: The goal is to find the lexicographically smallest string by performing the allowed swaps.
Steps:
• Use Union-Find (Disjoint Set Union) to group indices that can be connected through the given pairs.
• For each group, sort the indices and the characters in those positions.
• Assign the sorted characters back to the indices to form the smallest possible string.
Goal: The problem has constraints to ensure that the input size is manageable.
Steps:
• 1 <= s.length <= 10^5
• 0 <= pairs.length <= 10^5
• 0 <= pairs[i][0], pairs[i][1] < s.length
• s only contains lowercase English letters.
Assumptions:
• It is assumed that the input string s only contains lowercase English letters.
Input: Input: s = "zaxy", pairs = [[0,3],[1,2]]
Explanation: Swap s[0] and s[3], s = "yazx". Swap s[1] and s[2], s = "axyz".

Input: Input: s = "xyza", pairs = [[0,3],[1,2],[0,2]]
Explanation: Swap s[0] and s[3], s = "ayzx". Swap s[0] and s[2], s = "axyz".

Input: Input: s = "acdb", pairs = [[0,1],[1,2],[2,3]]
Explanation: Swap s[0] and s[1], s = "cabd". Swap s[1] and s[2], s = "cdab". Swap s[2] and s[3], s = "abcd".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus