Finding the largest 5 digit number within the input number using JavaScript

We need to write a JavaScript function that takes in a string number of at least five digits and returns the greatest sequence of five consecutive digits found within the input number.

Problem Statement

Given a number string, find all possible 5-digit consecutive sequences and return the largest one as a number.

Example

Let's implement the solution step by step:

const num = '123546544';

const findGreatestFiveDigit = (num = '') => {
    const str = num.toString();
    const arr = [];
    
    // Extract all 5-digit sequences
    for(let i = 0; i <= str.length - 5; i++){
        arr.push(str.slice(i, i + 5));
    }
    
    // Convert to numbers and find maximum
    return Math.max(...arr.map(Number));
};

console.log(findGreatestFiveDigit(num));
console.log("All 5-digit sequences:", num.match(/.{1,5}/g));
54654
All 5-digit sequences: [ '12354', '23546', '35465', '54654', '46544' ]

How It Works

The algorithm works by:

  • Converting the input to a string to handle digit extraction
  • Using a loop to extract all possible 5-digit substrings
  • Using slice(i, i + 5) to get consecutive sequences
  • Converting string sequences back to numbers for comparison
  • Using Math.max() with spread operator to find the largest

Enhanced Version with Validation

const findGreatestFiveDigit = (num = '') => {
    const str = num.toString();
    
    // Validation
    if (str.length < 5) {
        throw new Error('Input must have at least 5 digits');
    }
    
    let maxSequence = 0;
    
    // Find maximum 5-digit sequence
    for(let i = 0; i <= str.length - 5; i++){
        const sequence = parseInt(str.slice(i, i + 5));
        maxSequence = Math.max(maxSequence, sequence);
    }
    
    return maxSequence;
};

// Test cases
console.log(findGreatestFiveDigit('123546544'));  // 54654
console.log(findGreatestFiveDigit('987654321'));  // 98765
console.log(findGreatestFiveDigit('111119999'));  // 99999
54654
98765
99999

Key Points

  • The loop condition i ensures we don't go out of bounds
  • slice(i, i + 5) extracts exactly 5 characters starting at index i
  • Converting strings to numbers allows proper numerical comparison
  • Input validation prevents errors with insufficient digits

Conclusion

This solution efficiently finds the largest 5-digit sequence by iterating through all possible consecutive digit combinations. The time complexity is O(n) where n is the length of the input string.

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

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements