Maximum Value of a String in an Array - 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.

Input & Output

Example 1 — Mixed String Types
$ Input: strs = ["alic3","bob","3","4","00000"]
Output: 5
💡 Note: "alic3" has mixed characters, value = length = 5. "bob" has letters, value = length = 3. "3" is digits only, value = 3. "4" is digits only, value = 4. "00000" is digits only, value = 0. Maximum value is 5.
Example 2 — All Digit Strings
$ Input: strs = ["1","01","001","0001"]
Output: 1
💡 Note: All strings contain only digits. "1" = 1, "01" = 1, "001" = 1, "0001" = 1. Maximum value is 1.
Example 3 — Large Numbers vs Length
$ Input: strs = ["999","abcdefghijk"]
Output: 999
💡 Note: "999" is digits only, value = 999. "abcdefghijk" has letters, value = length = 11. Maximum value is 999.

Constraints

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

Visualization

Tap to expand
Maximum Value of a String in an Array INPUT strs = ["alic3","bob","3","4","00000"] "alic3" "bob" "3" "4" "00000" Value Calculations: "alic3" has letters len=5 "bob" has letters len=3 "3" digits only val=3 "4" digits only val=4 "00000" digits only val=0 ALGORITHM STEPS 1 Initialize max = 0 Track maximum value found 2 Loop through strings for each str in strs 3 Check if digits only Use isdigit() method str.isdigit() returns bool 4 Calculate value If digits: int(str) Else: len(str) def getValue(s): if s.isdigit(): return int(s) else: return len(s) FINAL RESULT Computed Values: alic3 5 bob 3 "3" 3 "4" 4 00000 0 Finding Maximum: max(5, 3, 3, 4, 0) Comparing all values... 5 is the largest! OUTPUT 5 Key Insight: The isdigit() built-in method efficiently checks if a string contains only numeric characters. For "alic3" and "bob", it returns False (use length). For "3", "4", "00000", it returns True (use int value). TutorialsPoint - Maximum Value of a String in an Array | Built-in String Methods Approach
Asked in
Google 15 Amazon 12
12.0K Views
Medium Frequency
~8 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen