String validation checks in Python - Time & Space Complexity
When we check if a string meets certain rules, like only letters or digits, the time it takes depends on the string's length.
We want to know how the time grows as the string gets longer.
Analyze the time complexity of the following code snippet.
def is_alpha(s):
for char in s:
if not char.isalpha():
return False
return True
This code checks if every character in the string is a letter. It stops early if it finds a non-letter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Up to once per character, depending on when a non-letter is found.
As the string gets longer, the function may check more characters, up to the full length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 character checks |
| 100 | Up to 100 character checks |
| 1000 | Up to 1000 character checks |
Pattern observation: The number of checks grows roughly in direct proportion to the string length.
Time Complexity: O(n)
This means the time to check grows in a straight line with the string length.
[X] Wrong: "The check always takes the same time no matter the string length."
[OK] Correct: The function looks at each character until it finds a problem or finishes, so longer strings usually take more time.
Understanding how string checks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed the check to look for digits instead of letters? How would the time complexity change?"