Created
April 27, 2021 01:56
-
-
Save mfaani/be2bf1b81d76e196fa46d8356c23b9c5 to your computer and use it in GitHub Desktop.
// Remove K Digits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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