We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Value of a String in an Array

Number: 2589

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an array of alphanumeric strings, determine the "value" of each string as follows: if the string contains only digits, its value is the numeric value (with leading zeros ignored); if it contains any letters, its value is simply the length of the string. Return the maximum value among all strings in the array.


Key Insights

  • For each string, check if it is composed solely of digits.
  • If it is, convert it to an integer which automatically handles any leading zeros.
  • Otherwise, use the length of the string as its value.
  • Traverse the array once, calculating and updating the maximum value found.

Space and Time Complexity

Time Complexity: O(n * m) where n is the number of strings and m is the average length of each string (with m at most 9). Space Complexity: O(1) extra space, aside from the input.


Solution

We iterate through the array of strings. For each string, we determine if all characters are digits by checking each character. If the string is numeric, we convert it to an integer. Otherwise, we take the length of the string. We then update a variable tracking the maximum value seen so far. The approach leverages the built-in conversion and length functions, and is efficient considering the small maximum string length.


Code Solutions

# Function to calculate the maximum value of strings in the array
def maximumValue(strs):
    # Initialize maximum value to 0
    max_value = 0
    # Loop through each string in the list
    for s in strs:
        # Check if the string is composed only of digits
        if s.isdigit():
            # Convert the string to an integer (handles leading zeros automatically)
            value = int(s)
        else:
            # If not digits only, the value is the length of the string
            value = len(s)
        # Update max_value if the current value is larger
        max_value = max(max_value, value)
    return max_value

# Example usage:
print(maximumValue(["alic3", "bob", "3", "4", "00000"]))  # Expected output: 5
← Back to All Questions