Skip to main content

2434.js

/** ------------------------------------------------------------------------------
*
* 2434. Using a Robot to Print the Lexicographically Smallest String
* Topics: Hash Table, Greedy
* https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/description/?envType=daily-question&envId=2025-06-06
*
------------------------------------------------------------------------------ */
/**
* @param {string} s
* @return {string}
*/
var robotWithString = function (s) {
const charCount = Array(26).fill(0)
for (const char of s) {
charCount[char.charCodeAt(0) - 97]++
}

const stack = []
let minCharIndex = 0
let result = ""

for (const char of s) {
stack.push(char)
charCount[char.charCodeAt(0) - 97]--

while (minCharIndex < 26 && charCount[minCharIndex] === 0) {
minCharIndex++
}

while (stack.length && (minCharIndex === 26 || stack[stack.length - 1].charCodeAt(0) - 97 <= minCharIndex)) {
result += stack.pop()
}
}

while (stack.length) {
result += stack.pop()
}

return result
}

console.log()