Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the maximum number using at most one swap in JavaScript
We are required to write a JavaScript function that takes in a number as the first and the only argument.
The task of our function is to perform at most one swap between any two digits of the number and yield the maximum possible number. If the number is already the maximum possible number, we should return the number itself.
For example, if the input number is:
const num = 1625;
Then the output should be:
const output = 6125;
We swapped 1 and 6, and this is the only swap that yields the greatest number in a single swap.
How the Algorithm Works
The solution involves two main steps:
- Find the maximum digit: We use a recursive helper function to find the largest digit in the number.
- Perform optimal swap: We locate the first position where we can swap with the maximum digit to get the largest possible result.
Example
The code for this will be:
const num = 1625;
const findMaximumDigit = (num, max = 0) => {
if (!num) {
return max;
}
return findMaximumDigit(Math.floor(num / 10), Math.max(max, num % 10));
};
const makeOneSwap = (num = 1) => {
let i = 0;
const max = findMaximumDigit(num);
const numStr = String(num);
const numArr = numStr.split('');
const maxIndex = numStr.lastIndexOf('' + max);
while (i < maxIndex) {
if (+numStr[i] < max) {
let temp = numArr[i];
numArr[i] = numArr[maxIndex];
numArr[maxIndex] = temp;
break;
}
i++;
}
return +(numArr.join(''));
};
console.log(makeOneSwap(num));
Output
The output in the console will be:
6125
Step-by-Step Breakdown
Let's trace through the example with number 1625:
-
findMaximumDigit(1625)returns 6 (the largest digit) - Convert number to string array: ['1', '6', '2', '5']
- Find the last occurrence of '6' at index 1
- Start from index 0: '1'
- Result: ['6', '1', '2', '5'] ? 6125
Testing with More Examples
console.log(makeOneSwap(2736)); // 7236 (swap 2 and 7) console.log(makeOneSwap(9321)); // 9321 (already maximum) console.log(makeOneSwap(1234)); // 4231 (swap 1 and 4)
7236 9321 4231
Conclusion
This algorithm efficiently finds the maximum number possible with at most one swap by identifying the largest digit and swapping it with the first smaller digit from the left. The time complexity is O(n) where n is the number of digits.
