LeetCode Entry
1861. Rotating the Box
Rotate and simulate gravity in matrix
1861. Rotating the Box medium substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1351
Problem TLDR
Rotate and simulate gravity in matrix
Intuition
- first simulate ‘.’ bubble left or ‘#’ bubble right
- then rotate
Approach
- to bubble ‘.’ left: overwrite it with ‘#’ then overwrite empty place with ‘.’
- another solution is to split by ‘*’ chunks and sort them
Complexity
-
Time complexity: \(O(n|nlogn)\)
-
Space complexity: \(O(n)\)
Code
fun rotateTheBox(b: Array<CharArray>) = b.map { r ->
var j = 0
for (i in r.indices)
if (r[i] == '.') { r[i] = '#'; r[j++] = '.' }
else if (r[i] == '*') j = i+1
}.let { List(b[0].size) { i -> List(b.size) { b[b.size-1-it][i] }} }
pub fn rotate_the_box(mut b: Vec<Vec<char>>) -> Vec<Vec<char>> {
for r in &mut b {
for c in r.split_mut(|&c|c=='*') { c.sort_by(|a,b|b.cmp(a)) }};
(0..b[0].len()).map(|x|b.iter().rev().map(|r|r[x]).collect()).collect()
}