Skip to content

Instantly share code, notes, and snippets.

@mfaani
Created April 27, 2021 01:56
Show Gist options
  • Save mfaani/be2bf1b81d76e196fa46d8356c23b9c5 to your computer and use it in GitHub Desktop.
Save mfaani/be2bf1b81d76e196fa46d8356c23b9c5 to your computer and use it in GitHub Desktop.
// Remove K Digits
class Solution {
func removeKdigits(_ num: String, _ k: Int) -> String {
var drops = k
var maxStack: [Character] = []
for digit in num {
// only if there is something bigger in the stack to drop...
while drops > 0 && !maxStack.isEmpty && maxStack.last! > digit {
maxStack.popLast()
drops -= 1
}
// every 'new' digit gets appended, but that's only after some previous max is removed
maxStack.append(digit)
}
maxStack.removeLast(drops)
while maxStack.first == "0" {
maxStack.removeFirst()
}
if maxStack.isEmpty {
return "0"
}
return String(maxStack)
}
}
// [1,2,3,4,5,2,6,4]
// What did I learn:
/*
1. identify fixes / rough edge cases that can happen and need fixing e.g. starting with 0 or not having removed all values.
2. looping over a string gives you characters
3. you can compare characters and strings...
4. don't be afraid to loop twice. Get the job done...nor of having too many conditions for your while loop...
5. core logic: add every new digit, while also dropping maxes that are bigger than current digits
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment