402. Remove K Digits #144
-
Topics: Given string num representing a non-negative integer Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a greedy approach with a stack. The goal is to build the smallest possible number by iteratively removing digits from the given number while maintaining the smallest possible sequence. Approach:
Let's implement this solution in PHP: 402. Remove K Digits <?php
/**
* @param String $num
* @param Integer $k
* @return String
*/
function removeKdigits($num, $k) {
$stack = [];
$len = strlen($num);
for ($i = 0; $i < $len; $i++) {
$digit = $num[$i];
// Remove digits from the stack if the current digit is smaller and we still have digits to remove
while ($k > 0 && !empty($stack) && end($stack) > $digit) {
array_pop($stack);
$k--;
}
// Push the current digit onto the stack
$stack[] = $digit;
}
// If we still have digits to remove, remove them from the end
while ($k > 0) {
array_pop($stack);
$k--;
}
// Build the final result, removing leading zeros
$result = ltrim(implode('', $stack), '0');
// Return "0" if the result is empty
return $result === '' ? '0' : $result;
}
// Example usage:
echo removeKdigits("1432219", 3); // Output: "1219"
echo removeKdigits("10200", 1); // Output: "200"
echo removeKdigits("10", 2); // Output: "0"
?> Explanation:
Time Complexity:The time complexity of this solution is (O(n)), where This solution efficiently handles the constraints and provides the correct output for the given examples. |
Beta Was this translation helpful? Give feedback.
We can use a greedy approach with a stack. The goal is to build the smallest possible number by iteratively removing digits from the given number while maintaining the smallest possible sequence.
Approach:
k
digits to remove, pop the stack to remove the larger digits.num
, remove them from the end of the stack.