Obtaining maximum number via rotating digits in JavaScript

We are required to write a JavaScript function that takes in a positive integer n and returns the maximum number we can get by performing only left rotations on the digits of the number.

Problem

Left rotation means moving the first digit to the end. For example, rotating 12345 once gives 23451, rotating again gives 34512, and so on. We need to find which rotation produces the largest number.

Example

Let's implement the solution to find the maximum number through left rotations:

const num = 56789;

const findMaximum = (num = 1) => {
    let splitNumbers = num.toString().split("");
    let largestNumber = num;
    
    for(let i = 0; i < splitNumbers.length - 1; i++) {
        // Perform left rotation by moving first element to end
        splitNumbers.push(splitNumbers.shift());
        let newNumber = Number(splitNumbers.join(""));
        
        if(newNumber > largestNumber) {
            largestNumber = newNumber;
        }
    }
    
    return largestNumber;
};

console.log(findMaximum(num));
89567

How It Works

The algorithm converts the number to an array of digits, then performs left rotations by moving the first digit to the end using shift() and push(). Each rotation creates a new number that is compared with the current maximum.

Step-by-Step Rotations

const demonstrateRotations = (num) => {
    let digits = num.toString().split("");
    console.log(`Original: ${digits.join("")}`);
    
    for(let i = 0; i < digits.length - 1; i++) {
        digits.push(digits.shift());
        console.log(`Rotation ${i + 1}: ${digits.join("")}`);
    }
};

demonstrateRotations(56789);
Original: 56789
Rotation 1: 67895
Rotation 2: 78956
Rotation 3: 89567
Rotation 4: 95678

Optimized Version

Here's a more efficient approach that generates all rotations without modifying the original array:

const findMaximumOptimized = (num) => {
    const str = num.toString();
    let maxNumber = num;
    
    for(let i = 1; i < str.length; i++) {
        const rotated = str.slice(i) + str.slice(0, i);
        const rotatedNumber = Number(rotated);
        
        if(rotatedNumber > maxNumber) {
            maxNumber = rotatedNumber;
        }
    }
    
    return maxNumber;
};

console.log(findMaximumOptimized(56789));
console.log(findMaximumOptimized(12345));
console.log(findMaximumOptimized(54321));
95678
51234
54321

Conclusion

Finding the maximum number through left rotations involves systematically rotating digits and tracking the largest value. The optimized version using string slicing is more efficient than array manipulation for this specific problem.

Updated on: 2026-03-15T23:19:00+05:30

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements