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 −
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