Maximum max numeric value in a string

Last Updated : 10 May, 2026

Given an alphanumeric string s consisting of lowercase letters (a–z), uppercase letters (A–Z), and digits (0–9).
Extract all numeric substrings from s and return the maximum numeric value among them.
If no numeric substring exists, return -1.

Input : s = 100klh564abc365bg
Output : 564
Explanation: Maximum numeric value among 100, 564 and 365 is 564.

Input : s = abchsd0sdhs
Output : 0

Try It Yourself
redirect icon

[Naive Approach] Using String Traversal – O(n) Time and O(1) Space

The idea is to scan the string character by character and extract numbers formed by consecutive digits. Whenever a digit is encountered, we build the number by multiplying the current value by 10 and adding the new digit. When a non-digit character appears, it means the current number has ended, so we compare it with the maximum found so far. This process ensures that all numeric substrings are considered, and the largest one is returned.

  • Traverse the string and keep forming a number when consecutive digits are found
  • When a non-digit character appears, compare the formed number with the maximum and reset it
  • Return the maximum value at the end.
C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// Function to extract the maximum value
int extractMaximum(string &s)
{
    int num = 0, res = -1; 
    bool found = false;      
    
    // Start traversing the given string
    for (int i = 0; i < s.length(); i++)
    {
        // If a numeric value comes, start converting
        // it into an integer till there are consecutive
        // numeric digits
        if (s[i] >= '0' && s[i] <= '9') {
            num = num * 10 + (s[i] - '0');
            found = true;   // Mark that we found a digit
        }

        // Else Update maximum value
        else 
        {
            if (found) {   // Update only if number exists
                res = max(res, num);
                num = 0;       // Reset the number
                found = false; // Reset flag
            }
        }
    }

    // Return maximum value (check last number)
    if (found) {
        res = max(res, num);
    }

    return res;
}

// Driver program
int main()
{
    string s = "100klh564abc365bg";
    cout << extractMaximum(s);
    return 0;
}
Java
import java.util.*;

class GFG {
    
    // Function to extract the maximum value
    static int extractMaximum(String s)
    {
        int num = 0, res = -1; 
        boolean found = false;      
        
        // Start traversing the given string
        for (int i = 0; i < s.length(); i++)
        {
            // If a numeric value comes, start converting
            // it into an integer till there are consecutive
            // numeric digits
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                num = num * 10 + (s.charAt(i) - '0');
                found = true;   // Mark that we found a digit
            }

            // Else Update maximum value
            else
            {
                if (found) {   // Update only if number exists
                    res = Math.max(res, num);
                    num = 0;       // Reset the number
                    found = false; // Reset flag
                }
            }
        }

        // Return maximum value (check last number)
        if (found) {
            res = Math.max(res, num);
        }

        return res;
    }
    
    // Driver program
    public static void main(String[] args)
    {
        String s = "100klh564abc365bg";
        System.out.println(extractMaximum(s));
    }
}
Python
# Function to extract the maximum value
def extractMaximum(s):
    num = 0
    res = -1
    found = False      

    # Start traversing the given string
    for i in range(len(s)):
        # If a numeric value comes, start converting
        # it into an integer till there are consecutive
        # numeric digits
        if '0' <= s[i] <= '9':
            num = num * 10 + (ord(s[i]) - ord('0'))
            found = True   # Mark that we found a digit

        # Else Update maximum value
        else:
            if found:   # Update only if number exists
                res = max(res, num)
                num = 0       # Reset the number
                found = False # Reset flag

    # Return maximum value (check last number)
    if found:
        res = max(res, num)

    return res


# Driver program
s = "100klh564abc365bg"
print(extractMaximum(s))
C#
using System;

class GFG {

    // Function to extract the maximum value
    static int extractMaximum(string s)
    {
        int num = 0, res = -1; 
        bool found = false;      

        // Start traversing the given string
        for (int i = 0; i < s.Length; i++)
        {
            // If a numeric value comes, start converting
            // it into an integer till there are consecutive
            // numeric digits
            if (s[i] >= '0' && s[i] <= '9') {
                num = num * 10 + (s[i] - '0');
                found = true;   // Mark that we found a digit
            }

            // Else Update maximum value
            else
            {
                if (found) {   // Update only if number exists
                    res = Math.Max(res, num);
                    num = 0;       // Reset the number
                    found = false; // Reset flag
                }
            }
        }

        // Return maximum value (check last number)
        if (found) {
            res = Math.Max(res, num);
        }

        return res;
    }

    // Driver program
    public static void Main()
    {
        string s = "100klh564abc365bg";
        Console.WriteLine(extractMaximum(s));
    }
}
JavaScript
// Function to extract the maximum value
function extractMaximum(s)
{
    let num = 0, res = -1; 
    let found = false;      
    
    // Start traversing the given string
    for (let i = 0; i < s.length; i++)
    {
        // If a numeric value comes, start converting
        // it into an integer till there are consecutive
        // numeric digits
        if (s[i] >= '0' && s[i] <= '9') {
            num = num * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));
            found = true;   // Mark that we found a digit
        }

        // Else Update maximum value
        else
        {
            if (found) {   // Update only if number exists
                res = Math.max(res, num);
                num = 0;       // Reset the number
                found = false; // Reset flag
            }
        }
    }

    // Return maximum value (check last number)
    if (found) {
        res = Math.max(res, num);
    }

    return res;
}

// Driver program
let s = "100klh564abc365bg";
console.log(extractMaximum(s));

Output
564

[Optimal Approach] Using String Comparison (Handles Large Numbers) – O(n) Time and O(1) Space

Instead of converting numbers into integers (which may overflow for very large values), we treat them as strings and compare them directly. While traversing the string, we build numeric substrings and ignore leading zeros. Whenever a non-digit character is encountered, we compare the current number string with the maximum found so far based on length first (longer means larger) and lexicographically if lengths are equal. This ensures accurate comparison even for very large numbers.

  • Traverse the string and build numeric substrings while ignoring leading zeros
  • When a non-digit is encountered, finalize the current number and handle edge case of only zeros
  • Compare the current number with the result using length and lexicographical comparison
  • After traversal, process the last number and return the maximum or "-1" if none found
C++
#include<bits/stdc++.h>
using namespace std;

// Utility function to find maximum string
string maximumNum(string curr_num, string res)
{
    if (res == "") return curr_num;
    if (curr_num == "") return res;

    int len1 = curr_num.length();
    int len2 = res.length();

    if (len1 == len2)
    {
        int i = 0;
        while (i < len1 && curr_num[i] == res[i])
            i++;

        if (i < len1 && curr_num[i] < res[i])
            return res;
        else
            return curr_num;
    }

    return len1 < len2 ? res : curr_num;
}

// Function to extract the maximum value
string extractMaximum(string S)
{
    int n = S.length();
    string curr_num = "";
    string res = "";
    bool foundDigit = false;   

    for (int i = 0; i < n; i++)
    {
        // If digit found
        if (S[i] >= '0' && S[i] <= '9')
        {
            foundDigit = true;

            // Ignore leading zeroes
            if (curr_num == "" && S[i] == '0')
                continue;

            curr_num += S[i];
        }
        else
        {
            if (foundDigit)
            {
                // if only zeros → treat as "0"
                if (curr_num == "")
                    curr_num = "0";

                res = maximumNum(curr_num, res);

                curr_num = "";
                foundDigit = false;
            }
        }
    }

    // handle last number
    if (foundDigit)
    {
        if (curr_num == "")
            curr_num = "0";

        res = maximumNum(curr_num, res);
    }

    // if no number found
    if (res == "")
        return "-1";

    return res;
}

// Driver
int main()
{
    string S = "100klh564abc365bg";
    cout << extractMaximum(S) << endl;
    return 0;
}
Java
import java.util.*;

class GFG {

    // Utility function to find maximum string
    static String maximumNum(String curr_num, String res)
    {
        if (res.equals("")) return curr_num;
        if (curr_num.equals("")) return res;

        int len1 = curr_num.length();
        int len2 = res.length();

        if (len1 == len2)
        {
            int i = 0;
            while (i < len1 && curr_num.charAt(i) == res.charAt(i))
                i++;

            if (i < len1 && curr_num.charAt(i) < res.charAt(i))
                return res;
            else
                return curr_num;
        }

        return (len1 < len2) ? res : curr_num;
    }

    // Function to extract the maximum value
    static String extractMaximum(String S)
    {
        int n = S.length();
        String curr_num = "";
        String res = "";
        boolean foundDigit = false;  

        for (int i = 0; i < n; i++)
        {
            // If digit found
            if (S.charAt(i) >= '0' && S.charAt(i) <= '9')
            {
                foundDigit = true;

                // Ignore leading zeroes
                if (curr_num.equals("") && S.charAt(i) == '0')
                    continue;

                curr_num += S.charAt(i);
            }
            else
            {
                if (foundDigit)
                {
                    // if only zeros → treat as "0"
                    if (curr_num.equals(""))
                        curr_num = "0";

                    res = maximumNum(curr_num, res);

                    curr_num = "";
                    foundDigit = false;
                }
            }
        }

        // handle last number
        if (foundDigit)
        {
            if (curr_num.equals(""))
                curr_num = "0";

            res = maximumNum(curr_num, res);
        }

        // if no number found
        if (res.equals(""))
            return "-1";

        return res;
    }

    // Driver
    public static void main(String[] args)
    {
        String S = "100klh564abc365bg";
        System.out.println(extractMaximum(S));
    }
}
Python
# Utility function to find maximum string
def maximumNum(curr_num, res):
    if res == "": return curr_num
    if curr_num == "": return res

    len1 = len(curr_num)
    len2 = len(res)

    if len1 == len2:
        i = 0
        while i < len1 and curr_num[i] == res[i]:
            i += 1

        if i < len1 and curr_num[i] < res[i]:
            return res
        else:
            return curr_num

    return res if len1 < len2 else curr_num


# Function to extract the maximum value
def extractMaximum(S):
    n = len(S)
    curr_num = ""
    res = ""
    foundDigit = False   

    for i in range(n):
        # If digit found
        if '0' <= S[i] <= '9':
            foundDigit = True

            # Ignore leading zeroes
            if curr_num == "" and S[i] == '0':
                continue

            curr_num += S[i]
        else:
            if foundDigit:
                # if only zeros → treat as "0"
                if curr_num == "":
                    curr_num = "0"

                res = maximumNum(curr_num, res)

                curr_num = ""
                foundDigit = False

    # handle last number
    if foundDigit:
        if curr_num == "":
            curr_num = "0"

        res = maximumNum(curr_num, res)

    # if no number found
    if res == "":
        return "-1"

    return res


# Driver
S = "100klh564abc365bg"
print(extractMaximum(S))
C#
using System;

class GFG {

    // Utility function to find maximum string
    static string maximumNum(string curr_num, string res)
    {
        if (res == "") return curr_num;
        if (curr_num == "") return res;

        int len1 = curr_num.Length;
        int len2 = res.Length;

        if (len1 == len2)
        {
            int i = 0;
            while (i < len1 && curr_num[i] == res[i])
                i++;

            if (i < len1 && curr_num[i] < res[i])
                return res;
            else
                return curr_num;
        }

        return len1 < len2 ? res : curr_num;
    }

    // Function to extract the maximum value
    static string extractMaximum(string S)
    {
        int n = S.Length;
        string curr_num = "";
        string res = "";
        bool foundDigit = false; 

        for (int i = 0; i < n; i++)
        {
            // If digit found
            if (S[i] >= '0' && S[i] <= '9')
            {
                foundDigit = true;

                // Ignore leading zeroes
                if (curr_num == "" && S[i] == '0')
                    continue;

                curr_num += S[i];
            }
            else
            {
                if (foundDigit)
                {
                    // if only zeros → treat as "0"
                    if (curr_num == "")
                        curr_num = "0";

                    res = maximumNum(curr_num, res);

                    curr_num = "";
                    foundDigit = false;
                }
            }
        }

        // handle last number
        if (foundDigit)
        {
            if (curr_num == "")
                curr_num = "0";

            res = maximumNum(curr_num, res);
        }

        // if no number found
        if (res == "")
            return "-1";

        return res;
    }

    // Driver
    public static void Main()
    {
        string S = "100klh564abc365bg";
        Console.WriteLine(extractMaximum(S));
    }
}
JavaScript
// Utility function to find maximum string
function maximumNum(curr_num, res)
{
    if (res === "") return curr_num;
    if (curr_num === "") return res;

    let len1 = curr_num.length;
    let len2 = res.length;

    if (len1 === len2)
    {
        let i = 0;
        while (i < len1 && curr_num[i] === res[i])
            i++;

        if (i < len1 && curr_num[i] < res[i])
            return res;
        else
            return curr_num;
    }

    return len1 < len2 ? res : curr_num;
}

// Function to extract the maximum value
function extractMaximum(S)
{
    let n = S.length;
    let curr_num = "";
    let res = "";
    let foundDigit = false;  

    for (let i = 0; i < n; i++)
    {
        // If digit found
        if (S[i] >= '0' && S[i] <= '9')
        {
            foundDigit = true;

            // Ignore leading zeroes
            if (curr_num === "" && S[i] === '0')
                continue;

            curr_num += S[i];
        }
        else
        {
            if (foundDigit)
            {
                // if only zeros → treat as "0"
                if (curr_num === "")
                    curr_num = "0";

                res = maximumNum(curr_num, res);

                curr_num = "";
                foundDigit = false;
            }
        }
    }

    // handle last number
    if (foundDigit)
    {
        if (curr_num === "")
            curr_num = "0";

        res = maximumNum(curr_num, res);
    }

    // if no number found
    if (res === "")
        return "-1";

    return res;
}

// Driver
let S = "100klh564abc365bg";
console.log(extractMaximum(S));

Output
564
Comment