Kotlin | Rust
Join me on Telegramhttps://t.me/leetcode_daily_unstoppable/835Problem TLDRMax lexical ordered with repeat_limit string #medium #bucket_sortIntuitionAlways peek
![1.webp](https://assets.leetcode.com/users/images/7d00b443-ca29-46f4-8852-cab7eef32ef1_1734425669.3229325.webp)\n\nhttps://youtu.be/tGaNBtqpNec\n\n#### Join me on Telegram\n\nhttps://t.me/leetcode_daily_unstoppable/835\n\n#### Problem TLDR\n\nMax lexical ordered with `repeat_limit` string #medium #bucket_sort\n\n#### Intuition\n\nAlways peek the largest value. If limit is reached peek one of the next.\n\n#### Approach\n\n* we can use a heap, but have to manage all the next chars at once\n* we can use a frequency counter and two pointers: current and next \n\n#### Complexity\n\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n#### Code\n\n```kotlin []\n\n    fun repeatLimitedString(s: String, repeatLimit: Int) = buildString {\n        val f = IntArray(26); for (c in s) f[c - \'a\']++\n        var cnt = 0; var i = 25; var j = i\n        while (i >= 0) {\n            if (f[i] == 0) { i--; continue }\n            if (length == 0 || get(length - 1) == \'a\' + i) cnt++ else cnt = 1\n            if (cnt > repeatLimit) {\n                j = min(j, i - 1); while (j >= 0 && f[j] == 0) j--\n                if (j >= 0) { append(\'a\' + j); f[j]-- } else break\n            } else { append(\'a\' + i); f[i]-- }\n        }\n    }\n\n```\n```rust []\n\n    pub fn repeat_limited_string(s: String, repeat_limit: i32) -> String {\n        let mut f = [0; 26]; for b in s.bytes() { f[(b - b\'a\') as usize] += 1 }\n        let (mut cnt, mut i, mut j, mut r) = (0, 25, 25, vec![]);\n        loop {\n            if f[i] == 0 { if i == 0 { break } else { i -= 1; continue }}\n            if r.last().map_or(true, |&l| l == b\'a\' + i as u8) { cnt += 1 } else { cnt = 1 }\n            if cnt > repeat_limit {\n                if i == 0 { break } else { j = j.min(i - 1) }\n                loop { if j == 0 || f[j] > 0 { break } else { j -= 1 }}\n                if f[j] > 0 { r.push(b\'a\' + j as u8); f[j] -= 1 } else { break }\n            } else { r.push(b\'a\' + i as u8); f[i] -= 1}\n        }; String::from_utf8(r).unwrap()\n    }\n\n```\n```c++ []\n\n    string repeatLimitedString(string s, int repeatLimit) {\n        int f[26]; for (auto c: s) ++f[c - \'a\'];\n        int cnt = 0, i = 25, j = 25, l = 26; string r;\n        while (i >= 0) {\n            if (!f[i]) { --i; continue; }\n            l == i ? ++cnt : cnt = 1;\n            if (cnt > repeatLimit) {\n                j = min(j, i - 1);\n                while (j > 0 && !f[j]) --j;\n                if (j >= 0 && f[j]--) { r += \'a\' + j; l = j; } else break;\n            } else { r += \'a\' + i; --f[i]; l = i; }\n        } return r;\n    }\n\n```
['Bucket Sort', 'C++', 'Rust', 'Kotlin']