Smallest number after removing n digits in JavaScript


We are required to write a JavaScript function that takes in two numbers, let’s call them m and n as first and the second argument respectively.

The task of our function is to remove n digits from the number m so that the number m is the smallest possible number after removing n digits. And finally, the function should return the number m after removing digits.

For example, if the input to the function is −

const m = '45456757';
const n = 3;

Then the output should be −

const output = '44557';

Output Explanation:

We removed 5, 6 and 7 digit to get the smallest possible number.


The code for this will be −

 Live Demo

const m = '45456757';
const n = 3;
const removeDigits = (m, n, stack = []) => {
   let arr = m.split('').map(Number);
   for(let el of arr){
      while (n && stack.length && el < stack[stack.length - 1]){
   let begin = stack.findIndex(el => el > 0);
   let end = stack.length - n;
   return (!stack.length || begin == -1 || begin == end) ? "0" : stack.slice(begin, end).join('').toString();
console.log(removeDigits(m, n));

Code Explanation:

We have here used a greedy algorithm using a stack to formulate the answer. For each value el of the input string num from left-to-right, we push el onto the stack after we have removed up to n values from the stack which are greater-than el.

Since the left-most positions of a number are more valuable than the right-most positions, this greedy approach ensures the left-most positions are composed of the smallest digits, and whatever is leftover in the stack is the largest digits in the right-most positions.

After the input string m has been processed if there are any remaining n digits to remove, then remove the right-most n digits, since the right-most n digits are the largest digits.


And the output in the console will be −