Smallest number formed by shuffling one digit at most in JavaScript


Problem

We are required to write a JavaScript function that takes in a positive number n. We can do at most one operation −

Choosing the index of a digit in the number, remove this digit at that index and insert it back to another or at the same place in the number in order to find the smallest number we can get.

Our function should return this smallest number.

Example

Following is the code −

 Live Demo

const num = 354166;
const smallestShuffle = (num) => {
   const arr = String(num).split('');
   const { ind } = arr.reduce((acc, val, index) => {
      let { value, ind } = acc;
      if(value > val){
         value = val;
         ind = index;
      };
      return { value, ind };
   }, { value: Infinity, ind: -1 });
   const [item] = arr.splice(ind, 1);
   arr.unshift(item);
   return Number(arr.join(''));
};
console.log(smallestShuffle(num));

Output

Following is the console output −

135466

Updated on: 19-Apr-2021

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements