Talentd
FleetCode
Make and follow sheets.Sign in

Maximum Value of a String in an Array solution and explanation

EasyArrayString5 min read74.2% acceptanceUpdated 9 Apr 2026
Leetcode | 2496. Maximum Value of a String in an Array | Easy | Java SolutionDeveloper Docs · 6:41 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. Leetcode | 2496. Maximum Value of a String in an Array | Easy | Java SolutionDeveloper Docs · 6:41 · 1K views
  2. Maximum Value of a String in an Array || leetcode Biweekly 93 || Leetcode EasyBinaryMagic · 6:54 · 899 views
  3. Leetcode 2496 Maximum Value of a String in an Array (Java)TheAnalyticGuy · 4:08 · 492 views
  4. Leetcode 2496 || Hindi (हिन्दी) ||Maximum Value of a String in an Array| Hindi(हिन्दी )CodeVed | Sanjib Asiwal · 10:25 · 449 views
  5. 2496. Maximum Value of a String in an Array (Leetcode Easy)Programming Live with Larry · 2:19 · 414 views
  6. Leetcode 6261|| Maximum Value of a String in an Array || Leetcode Contest Easy || cppCoding Techniques with Komal | Newton School · 7:28 · 356 views
  7. 6261. Maximum Value of a String in an Array || Leetcode biweekly contest 93 || Code in DescriptionCS warriors · 8:22 · 166 views
  8. leetcode 2496. Maximum Value of a String in an Array - string method isdigit() or soCode-Yao · 6:12 · 126 views
  9. 2496 Maximum Value of a String in an Array with Python | Leetcode with python #python #leetcodeArsalan Ahmed · 7:44 · 124 views
  10. Maximum Value Of A String In An ArrayOwen Wu · 1:47 · 119 views

The problem

The value of an alphanumeric string can be defined as:

  • The numeric representation of the string in base 10, if it comprises of digits only.
  • The length of the string, otherwise.

Given an array strs of alphanumeric strings, return the maximum value of any string in strs.

Example 1:

Input: strs = ["alic3","bob","3","4","00000"]
Output: 5
Explanation: 
- "alic3" consists of both letters and digits, so its value is its length, i.e. 5.
- "bob" consists only of letters, so its value is also its length, i.e. 3.
- "3" consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4" also consists only of digits, so its value is 4.
- "00000" consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3".

Example 2:

Input: strs = ["1","01","001","0001"]
Output: 1
Explanation: 
Each string in the array has value 1. Hence, we return 1.

Constraints:

  • 1 <= strs.length <= 100
  • 1 <= strs[i].length <= 9
  • strs[i] consists of only lowercase English letters and digits.

Approach overview

Problem Overview: You receive an array of strings. Each string represents a value using two different rules: if the string contains only digits, its value is the integer it represents; otherwise its value is simply its length. Your task is to compute the maximum value across all strings.

The challenge is classification. For every string, you must determine whether it is numeric or alphanumeric. Once classified, compute either the integer value or the length, then keep track of the maximum. The problem mainly tests careful string inspection and efficient iteration through an array.

Approach 1: Iterative Classification (O(n * m) time, O(1) space)

Iterate through the array once and classify each string character-by-character. For each string, scan all characters and check whether every character falls between '0' and '9'. If a non-digit appears, the string is treated as a regular word and its value becomes len(s). If every character is a digit, convert it to an integer using stoi, parseInt, or equivalent.

Track the maximum value while iterating. The algorithm performs a single pass over the array and a scan over each string. If n is the number of strings and m is the maximum string length, the complexity becomes O(n * m). No additional data structures are required, so the space complexity stays O(1). This approach is straightforward, language‑agnostic, and the most common solution used in interviews.

Approach 2: Classification with Helper Functions (O(n * m) time, O(1) space)

This variation extracts the classification logic into helper functions. One helper checks whether a string is numeric using built-in checks like isdigit(), regular expressions, or a small digit-validation loop. Another helper computes the value: return the parsed integer if numeric, otherwise return the string length.

The main loop simply calls the helper for each string and updates the maximum value. Complexity remains O(n * m) because every character may still be inspected during validation. Space usage stays O(1) since no extra structures are allocated beyond a few variables.

The benefit is readability. Separating classification logic keeps the main loop clean and easier to maintain, especially in languages like JavaScript or Python where helper functions are lightweight.

Recommended for interviews: The iterative classification approach is typically expected. It demonstrates that you can reason about character ranges, iterate efficiently, and maintain running results. The helper-function version is also valid and slightly cleaner in production-style code, but interviewers mainly care that you correctly classify numeric strings and achieve the linear O(n * m) solution.

Approach 1: Iterative Classification

In this approach, we iterate over each string in the array and classify it as either purely numeric or alphanumeric. For numeric strings, we convert them to an integer value using base 10, and for alphanumeric strings, we use their length as the value. We keep track of the maximum value encountered during this iteration.

def maximum_value_of_string_in_array(strs):
    max_value = 0
    for s in strs:
        # Check if the string is purely numeric
        if s.isdigit():
            value = int(s)
        else:
            value = len(s)
        # Update max_value if current value is larger
        max_value = max(max_value, value)
    return max_value

# Example usage
print(maximum_value_of_string_in_array(["alic3","bob","3","4","00000"]))  # Output: 5
public class MaxValueString {
    public static int maximumValue(String[] strs) {
        int maxValue = 0;
        for (String s : strs) {
            int value = s.matches("\\d+") ? Integer.parseInt(s) : s.length();
            maxValue = Math.max(maxValue, value);
        }
        return maxValue;
    }

    public static void main(String[] args) {
        String[] strs = {"alic3","bob","3","4","00000"};
        System.out.println(maximumValue(strs)); // Output: 5
    }
}
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int maximumValue(const std::vector<std::string>& strs) {
    int maxValue = 0;
    for (const std::string& s : strs) {
        int value = std::all_of(s.begin(), s.end(), ::isdigit) ? std::stoi(s) : s.length();
        maxValue = std::max(maxValue, value);
    }
    return maxValue;
}

int main() {
    std::vector<std::string> strs = {"alic3","bob","3","4","00000"};
    std::cout << maximumValue(strs) << std::endl;  // Output: 5
    return 0;
}
function maximumValue(strs) {
    let maxValue = 0;
    for (let s of strs) {
        let value = /^[0-9]+$/.test(s) ? parseInt(s, 10) : s.length;
        maxValue = Math.max(maxValue, value);
    }
    return maxValue;
}

// Example usage
console.log(maximumValue(["alic3","bob","3","4","00000"])); // Output: 5
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int maximumValue(char* strs[], int n) {
    int maxValue = 0;
    for (int i = 0; i < n; ++i) {
        int isNumeric = 1;
        for (int j = 0; j < strlen(strs[i]); ++j) {
            if (!isdigit(strs[i][j])) {
                isNumeric = 0;
                break;
            }
        }
        int value = isNumeric ? atoi(strs[i]) : strlen(strs[i]);
        if (value > maxValue) {
            maxValue = value;
        }
    }
    return maxValue;
}

int main() {
    char* strs[] = {"alic3","bob","3","4","00000"};
    int n = sizeof(strs) / sizeof(strs[0]);
    printf("%d\n", maximumValue(strs, n)); // Output: 5
    return 0;
}
using System;

class MaxValueString {
    public static int MaximumValue(string[] strs) {
        int maxValue = 0;
        foreach (string s in strs) {
            int value = int.TryParse(s, out int num) ? num : s.Length;
            maxValue = Math.Max(maxValue, value);
        }
        return maxValue;
    }

    static void Main(string[] args) {
        string[] strs = {"alic3","bob","3","4","00000"};
        Console.WriteLine(MaximumValue(strs)); // Output: 5
    }
}

This Python function iterates over each string in the given list. It checks if a string contains only digits using the method isdigit(). If it does, the string is converted to an integer. Otherwise, the length of the string is calculated and used as its value. The function keeps track of the maximum value encountered and returns it.

Complexity

The time complexity of this solution is O(n), where n is the total number of characters across all strings, and the space complexity is O(1) since we are only using a fixed amount of space for tracking the maximum value.

Try this approach in the editor

Approach 2: Classification with Helper Functions

This approach uses helper functions to separately determine if the string is numeric and to calculate the appropriate value. This modular design enhances readability and reusability of the code. We then find the maximum value using these helper functions.

def is_numeric(s):
    return s.isdigit()


def string_value(s):
    return int(s) if is_numeric(s) else len(s)


def maximum_value_of_string_in_array(strs):
    return max(map(string_value, strs))


# Example usage
print(maximum_value_of_string_in_array(["alic3", "bob", "3", "4", "00000"]))  # Output: 5
function isNumeric(s) {
    return /^[0-9]+$/.test(s);
}

function getStringValue(s) {
    return isNumeric(s) ? parseInt(s, 10) : s.length;
}

function maximumValue(strs) {
    return Math.max(...strs.map(getStringValue));
}

// Example usage
console.log(maximumValue(["alic3","bob","3","4","00000"])); // Output: 5

This Python solution uses the helper function is_numeric to check for numeric strings and string_value to calculate value. These functions are utilized in maximum_value_of_string_in_array to determine the maximum value by mapping string_value over all strings.

Complexity

The time complexity is O(n), where n is the total number of characters in all strings. Space complexity remains O(1), independent of input size.

Try this approach in the editor

Approach 3: Default Approach

function maximumValue(strs: string[]): number {
    const f = (s: string) => (Number.isNaN(Number(s)) ? s.length : Number(s));
    return Math.max(...strs.map(f));
}
func maximumValue(strs []string) (ans int) {
	f := func(s string) (x int) {
		for _, c := range s {
			if c >= 'a' && c <= 'z' {
				return len(s)
			}
			x = x*10 + int(c-'0')
		}
		return
	}
	for _, s := range strs {
		if x := f(s); ans < x {
			ans = x
		}
	}
	return
}
impl Solution {
    pub fn maximum_value(strs: Vec<String>) -> i32 {
        let mut ans = 0;
        for s in strs.iter() {
            let num = s.parse().unwrap_or(s.len());
            ans = ans.max(num);
        }
        ans as i32
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Iterative Classification

The time complexity of this solution is O(n), where n is the total number of characters across all strings, and the space complexity is O(1) since we are only using a fixed amount of space for tracking the maximum value.

Classification with Helper Functions

The time complexity is O(n), where n is the total number of characters in all strings. Space complexity remains O(1), independent of input size.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative ClassificationO(n * m)O(1)Best general solution; efficient single pass through the array
Classification with Helper FunctionsO(n * m)O(1)Cleaner code structure when separating validation and value logic

Frequently asked questions

Is Maximum Value of a String in an Array easy or hard?

Maximum Value of a String in an Array is classified as an Easy problem on LeetCode with an acceptance rate around 74%. The task mainly tests string inspection and basic iteration rather than complex data structures or algorithms.

Maximum Value of a String in an Array Python/Java solution

In Python, iterate through the list and use s.isdigit() to classify strings before applying int(s) or len(s). In Java, loop through the array and check characters using Character.isDigit before calling Integer.parseInt. Both implementations run in O(n * m) time and O(1) space.

How to solve Maximum Value of a String in an Array in O(n)?

You cannot strictly achieve O(n) if digit validation requires scanning characters. The practical optimal solution is O(n * m), where m is the maximum string length. Iterate through the array, check if each string is numeric, compute its value accordingly, and update the running maximum.

What is the best approach for Maximum Value of a String in an Array?

The best approach is a single-pass iterative classification. Scan each string, determine whether all characters are digits, and compute either the parsed integer value or the string length. Track the maximum during iteration. This runs in O(n * m) time where n is the number of strings and m is the maximum string length, with O(1) extra space.

Is Maximum Value of a String in an Array asked at Google/Amazon/Meta?

Problems of this style appear in coding interviews at companies like Amazon and Google as easy screening questions. They test basic string parsing, iteration, and attention to edge cases rather than advanced algorithms.

What data structure is used in Maximum Value of a String in an Array?

The core data structure is a simple array of strings. The algorithm processes the array sequentially and performs character checks on each string. No additional structures like hash maps or stacks are required.

What is the time complexity of Maximum Value of a String in an Array?

The time complexity is O(n * m). The algorithm iterates through n strings, and each string may require scanning up to m characters to verify whether it contains only digits. Space complexity remains O(1) because only a few variables are used to store the current value and maximum.

Comments

Now write it yourselfClose this page and solve Maximum Value of a String in an Array in the editor, without looking.
Practise Maximum Value of a String in an Array