2496. Maximum Value of a String in an Array
Problem Description
You are given an array of alphanumeric strings and need to find the maximum value among all strings, where the value of each string is determined by specific rules.
For any alphanumeric string, its value is calculated as follows:
- If the string contains only digits (like "123" or "007"), its value is the numeric representation in base 10. For example, "123" has a value of
123
, and "007" has a value of7
. - If the string contains any non-digit characters (like "a1b2" or "hello"), its value is simply the length of the string. For example, "a1b2" has a value of
4
, and "hello" has a value of5
.
Your task is to return the maximum value among all strings in the given array strs
.
Example scenarios:
-
For
strs = ["5", "abc", "12"]
:- "5" contains only digits → value =
5
- "abc" contains letters → value =
3
(length) - "12" contains only digits → value =
12
- Maximum value =
12
- "5" contains only digits → value =
-
For
strs = ["a1", "999", "xy"]
:- "a1" contains letters → value =
2
(length) - "999" contains only digits → value =
999
- "xy" contains letters → value =
2
(length) - Maximum value =
999
- "a1" contains letters → value =
The solution iterates through each string, applies the value calculation rule using a helper function f(s)
, and returns the maximum value found.
Intuition
The key insight is recognizing that we have two distinct types of strings with different valuation methods. We need a way to uniformly evaluate each string according to its type, then find the maximum among all these values.
When we look at any string, we first need to determine which category it falls into:
- Pure numeric strings (like "123") - these should be converted to their integer value
- Mixed or alphabetic strings (like "a1b" or "abc") - these should be evaluated by their length
The natural approach is to create a function that checks each character in the string. If all characters are digits, we treat it as a number and convert it using int()
. Otherwise, we count its length using len()
.
Once we can evaluate any single string correctly, finding the maximum becomes straightforward - we just apply this evaluation function to every string in the array and pick the largest result.
The elegance of this solution lies in its simplicity: we use Python's built-in all()
function with c.isdigit()
to check if every character is a digit. This gives us a clean boolean condition to decide between int(s)
and len(s)
. Then we leverage Python's max()
function with a generator expression to efficiently find the maximum value without storing intermediate results.
This approach is optimal because we only need to traverse each string once to determine its type and calculate its value, giving us O(n*m)
time complexity where n
is the number of strings and m
is the average string length.
Solution Approach
The implementation uses a helper function approach combined with Python's built-in functions for a clean and efficient solution.
Step 1: Define the evaluation function
We create a helper function f(s)
that determines the value of a single string:
def f(s: str) -> int:
return int(s) if all(c.isdigit() for c in s) else len(s)
This function works by:
- Using
all(c.isdigit() for c in s)
to check if every character in the string is a digit - If true, converting the string to an integer with
int(s)
- If false, returning the string's length with
len(s)
Step 2: Apply the function to all strings and find maximum
We use a generator expression with max()
to find the maximum value:
return max(f(s) for s in strs)
This approach:
- Iterates through each string
s
in the arraystrs
- Applies the evaluation function
f(s)
to get each string's value - Uses
max()
to find and return the largest value
Algorithm walkthrough with example:
Given strs = ["5", "abc", "12"]
:
- Process "5":
all(c.isdigit() for c in "5")
returnsTrue
→ value =int("5")
=5
- Process "abc":
all(c.isdigit() for c in "abc")
returnsFalse
→ value =len("abc")
=3
- Process "12":
all(c.isdigit() for c in "12")
returnsTrue
→ value =int("12")
=12
- Return
max(5, 3, 12)
=12
Time Complexity: O(n*m)
where n
is the number of strings and m
is the average length of strings (for checking digits in each string)
Space Complexity: O(1)
as we only use constant extra space (the generator expression doesn't create an intermediate list)
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with strs = ["42", "a1b", "9", "xyz"]
:
Step 1: Define our evaluation function
def f(s: str) -> int:
return int(s) if all(c.isdigit() for c in s) else len(s)
Step 2: Process each string
For "42"
:
- Check each character: '4' is digit ✓, '2' is digit ✓
all(c.isdigit() for c in "42")
returnsTrue
- Since all characters are digits, return
int("42")
= 42
For "a1b"
:
- Check each character: 'a' is NOT a digit ✗
all(c.isdigit() for c in "a1b")
returnsFalse
(stops early at 'a')- Since it contains non-digits, return
len("a1b")
= 3
For "9"
:
- Check the character: '9' is digit ✓
all(c.isdigit() for c in "9")
returnsTrue
- Since all characters are digits, return
int("9")
= 9
For "xyz"
:
- Check the first character: 'x' is NOT a digit ✗
all(c.isdigit() for c in "xyz")
returnsFalse
(stops early at 'x')- Since it contains non-digits, return
len("xyz")
= 3
Step 3: Find the maximum
max(f(s) for s in strs) # max(42, 3, 9, 3)
The values are: [42, 3, 9, 3]
The maximum value is 42.
Key observations:
- Pure digit strings get converted to their numeric value (potentially large)
- Mixed/alphabetic strings only count their length (typically small)
- The
all()
function short-circuits - it stops checking as soon as it finds a non-digit character, making the solution efficient
Solution Implementation
1class Solution:
2 def maximumValue(self, strs: List[str]) -> int:
3 """
4 Find the maximum value among all strings in the list.
5 For each string:
6 - If it contains only digits, its value is the integer it represents
7 - Otherwise, its value is its length
8
9 Args:
10 strs: List of strings to evaluate
11
12 Returns:
13 The maximum value among all strings
14 """
15
16 def get_string_value(string: str) -> int:
17 """
18 Calculate the value of a string based on its content.
19
20 Args:
21 string: The string to evaluate
22
23 Returns:
24 Integer value of the string if it's numeric, otherwise its length
25 """
26 # Check if all characters in the string are digits
27 if all(char.isdigit() for char in string):
28 # If yes, return the integer value of the string
29 return int(string)
30 else:
31 # If not, return the length of the string
32 return len(string)
33
34 # Find and return the maximum value among all strings
35 return max(get_string_value(string) for string in strs)
36
1class Solution {
2 /**
3 * Finds the maximum value among all strings in the array.
4 * For each string, the value is determined as:
5 * - If the string contains letters, its value is its length
6 * - If the string contains only digits, its value is its numeric value
7 *
8 * @param strs Array of strings to process
9 * @return The maximum value among all strings
10 */
11 public int maximumValue(String[] strs) {
12 int maxValue = 0;
13
14 // Iterate through each string and find the maximum value
15 for (String str : strs) {
16 maxValue = Math.max(maxValue, calculateStringValue(str));
17 }
18
19 return maxValue;
20 }
21
22 /**
23 * Calculates the value of a string based on its content.
24 * If the string contains any letter, returns its length.
25 * If the string contains only digits, returns its numeric value.
26 *
27 * @param str The string to evaluate
28 * @return The calculated value of the string
29 */
30 private int calculateStringValue(String str) {
31 int numericValue = 0;
32 int length = str.length();
33
34 // Check each character in the string
35 for (int i = 0; i < length; i++) {
36 char currentChar = str.charAt(i);
37
38 // If we encounter a letter, return the string length
39 if (Character.isLetter(currentChar)) {
40 return length;
41 }
42
43 // Build the numeric value digit by digit
44 numericValue = numericValue * 10 + (currentChar - '0');
45 }
46
47 // If no letters were found, return the numeric value
48 return numericValue;
49 }
50}
51
1class Solution {
2public:
3 int maximumValue(vector<string>& strs) {
4 // Lambda function to calculate the value of a string
5 // If string contains non-digit characters, return its length
6 // Otherwise, return its numeric value
7 auto calculateValue = [](string& str) {
8 int numericValue = 0;
9
10 // Iterate through each character in the string
11 for (char& ch : str) {
12 // If any character is not a digit, return string length
13 if (!isdigit(ch)) {
14 return static_cast<int>(str.size());
15 }
16 // Build the numeric value digit by digit
17 numericValue = numericValue * 10 + (ch - '0');
18 }
19
20 // All characters are digits, return the numeric value
21 return numericValue;
22 };
23
24 int maxValue = 0;
25
26 // Find the maximum value among all strings
27 for (auto& str : strs) {
28 maxValue = max(maxValue, calculateValue(str));
29 }
30
31 return maxValue;
32 }
33};
34
1/**
2 * Finds the maximum value from an array of strings.
3 * For each string:
4 * - If it represents a valid number, use its numeric value
5 * - Otherwise, use the length of the string
6 * Returns the maximum among all these values.
7 *
8 * @param strs - Array of strings to process
9 * @returns The maximum value according to the rules
10 */
11function maximumValue(strs: string[]): number {
12 /**
13 * Helper function to determine the value of a string.
14 * If the string can be converted to a number, return the number.
15 * Otherwise, return the length of the string.
16 *
17 * @param str - The string to evaluate
18 * @returns Either the numeric value or the string length
19 */
20 const getStringValue = (str: string): number => {
21 // Check if the string represents a valid number
22 const numericValue = Number(str);
23
24 // If conversion results in NaN, use string length; otherwise use the number
25 return Number.isNaN(numericValue) ? str.length : numericValue;
26 };
27
28 // Map each string to its value and find the maximum
29 const values = strs.map(getStringValue);
30 return Math.max(...values);
31}
32
Time and Space Complexity
Time Complexity: O(n * m)
where n
is the number of strings in the list and m
is the average length of the strings.
- The
max()
function iterates through alln
strings in the list - For each string
s
, the functionf(s)
is called - Inside
f(s)
,all(c.isdigit() for c in s)
checks every character in the string, which takesO(m)
time wherem
is the length of that string - Converting a string to integer with
int(s)
also takesO(m)
time - Getting the length with
len(s)
takesO(1)
time - Therefore, processing each string takes
O(m)
time, and processing alln
strings takesO(n * m)
time
Space Complexity: O(1)
auxiliary space
- The generator expression
(f(s) for s in strs)
usesO(1)
space as it yields values one at a time rather than creating a list - The function
f(s)
usesO(1)
auxiliary space for its operations - The
all()
function with generator expression also usesO(1)
space - No additional data structures are created that scale with input size
- Note: The input list itself takes
O(n * m)
space, but this is not counted as auxiliary space
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect String Validation Using str.isdigit()
Method
A common mistake is using str.isdigit()
directly on the entire string instead of checking each character:
Incorrect approach:
def get_string_value(string: str) -> int:
if string.isdigit(): # This won't work for leading zeros like "007"
return int(string)
else:
return len(string)
Why it fails:
- The
str.isdigit()
method returnsFalse
for empty strings, which could cause issues - More importantly, while this usually works, it's less explicit about what we're checking
Correct solution:
def get_string_value(string: str) -> int:
if all(char.isdigit() for char in string):
return int(string)
else:
return len(string)
2. Not Handling Empty Strings
The problem doesn't explicitly state whether empty strings are possible, but failing to consider them can cause runtime errors:
Problematic scenario:
strs = ["123", "", "abc"] # An empty string would pass the digit check but fail on int("")
Solution with edge case handling:
def get_string_value(string: str) -> int:
if string and all(char.isdigit() for char in string):
return int(string)
else:
return len(string) # Empty string returns 0
3. Using Regular Expressions Incorrectly
Some developers might try to use regex for digit checking but make pattern mistakes:
Incorrect regex approach:
import re
def get_string_value(string: str) -> int:
if re.match(r'\d+', string): # Wrong! This matches strings that START with digits
return int(string)
else:
return len(string)
Why it fails:
re.match(r'\d+', "123abc")
would return a match, butint("123abc")
would fail- The pattern should be
r'^\d+$'
to match entire string of digits
Correct regex solution:
import re
def get_string_value(string: str) -> int:
if re.match(r'^\d+$', string): # Anchored to match entire string
return int(string)
else:
return len(string)
4. Type Conversion Without Validation
Attempting to convert directly without checking can cause ValueError
:
Incorrect approach:
def get_string_value(string: str) -> int:
try:
return int(string)
except ValueError:
return len(string)
Why it's problematic: While this works functionally, it uses exception handling for control flow, which is:
- Less efficient than checking beforehand
- Less readable and explicit about intent
- Against Python best practices for predictable conditions
The original solution using all(char.isdigit() for char in string)
is cleaner and more efficient.
Which of the following problems can be solved with backtracking (select multiple)
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!