LeetCode Entry
1202. Smallest String With Swaps
Sort string by swapping pairs
1202. Smallest String With Swaps medium substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1560
Problem TLDR
Sort string by swapping pairs
Intuition
Use Union-Find to find the islands. Sort islands individually.
Approach
- we can use BinaryHeap
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
fun smallestStringWithSwaps(s: String, p: List<List<Int>>) = CharArray(s.length).apply {
val u = IntArray(s.length) { it }
fun f(x: Int): Int = if (u[x] == x) x else f(u[x]).also { u[x] = it }
for ((a, b) in p) u[f(a)] = f(b)
for (v in u.indices.groupBy(::f).values) v.zip(v.map(s::get).sorted(), ::set)
}.concatToString()
pub fn smallest_string_with_swaps(s: String, p: Vec<Vec<i32>>) -> String {
fn f(u: &mut [usize], x: usize) -> usize { if u[x] != x { u[x] = f(u, u[x]) } u[x] }
let (mut u, mut h, b) = ((0..s.len()).collect_vec(), vec![BinaryHeap::new(); s.len()], s.as_bytes());
for q in p { let (a, c) = (f(&mut u, q[0] as usize), f(&mut u, q[1] as usize)); u[a] = c }
for i in 0..b.len() { h[f(&mut u, i)].push(!b[i]) }
(0..b.len()).map(|i| !h[f(&mut u, i)].pop().unwrap() as char).collect()
}
Comments