Detect Capital using Python
Introduction
The Detect Capital problem asks whether a given word follows one of three valid capitalization patterns: all letters uppercase, all letters lowercase, or only the first letter uppercase with the rest lowercase. This seemingly simple task appears frequently on platforms such as LeetCode and serves as a quick litmus test for string manipulation proficiency.
Understanding the underlying rules helps developers avoid subtle bugs in user‑input validation, especially when processing names, product codes, or command‑line arguments where capitalization matters.
In the sections that follow, we will dissect the problem, explore the built‑in string methods that make the solution concise, and walk through a complete implementation with multiple alternative approaches.
Why It Matters
Correct capitalization detection is more than an academic exercise; it has practical implications in software that handles textual data. For instance, in the Voice Agent project, user‑spoken commands are transcribed and then checked for proper casing before being routed to intent classifiers.
When building APIs that accept user‑generated tags or usernames, enforcing a consistent capitalization scheme prevents duplicate entries caused by case variations such as "Google" versus "google" or "GOOGLE" .
Moreover, interviewers often use this problem to gauge a candidate’s ability to leverage Python’s standard library instead of resorting to verbose loops or regular expressions, which can be less efficient and harder to read.
Core Concepts
Three built‑in string methods are central to the solution: isupper(), islower(), and istitle(). Each returns a Boolean indicating whether the string meets a specific casing condition.
The isupper() method returns True only if all cased characters are uppercase and there is at least one cased character. Similarly, islower() checks for all lowercase cased characters. The istitle() method verifies title case: the first character is uppercase and all remaining cased characters are lowercase.
These methods operate in linear time relative to the length of the string because they scan each character once. They also use constant auxiliary space, making the overall algorithm O(n) time and O(1) space.
Edge cases such as a single‑character string (e.g., "a" or "Z\)) are naturally handled because a single uppercase letter satisfies isupper() while a single lowercase letter satisfies islower(). Both conditions return True, which aligns with the problem’s definition of valid capitalization.
Architecture and How It Works
The algorithm follows a straightforward decision tree. First, it tests whether the entire word is uppercase. If true, the function returns True immediately. If not, it checks for all lowercase. If that passes, it returns True. Finally, it evaluates title case; a match yields True. If none of the three checks succeed, the word is deemed incorrectly capitalized and the function returns False.
This ordering ensures that the most common patterns are caught early, minimizing unnecessary checks. Because each method short‑circuits on failure, the average case often performs better than the worst‑case O(n) bound.
Alternative architectures exist, such as iterating through characters and counting uppercase letters, but they require extra variables and more explicit logic, which can introduce bugs. The built‑in method approach leverages highly optimized C implementations within Python’s interpreter, giving it a performance edge.
In the Voice Agent project, a similar pattern is used to validate command keywords before they are dispatched to downstream services, demonstrating how this simple logic scales to larger systems.
Step‑by‑Step Implementation
Below is the canonical solution that uses the three string methods in sequence. The function is named detectCapitalUse and accepts a single string argument.
def detectCapitalUse(word: str) -> bool:
"""Return True if word uses capital letters correctly."""
if word.isupper():
return True
if word.islower():
return True
if word.istitle():
return True
return False
Each if statement corresponds to one of the valid patterns. The docstring clarifies the intent, making the code self‑explanatory for future maintainers.
An even more compact version expresses the same logic as a single return statement using the or operator:
def detectCapitalUse(word: str) -> bool:
return word.isupper() or word.islower() or word.istitle()
Although concise, some developers prefer the multi‑line variant for readability, especially when additional logging or debugging steps are needed.
For educational purposes, we can also implement the check manually with a loop. This version counts uppercase letters and validates the three allowed scenarios:
def detectCapitalUse_loop(word: str) -> bool:
if not word:
return True # empty string considered valid by convention
upper_count = sum(1 for ch in word if ch.isupper())
# all uppercase
if upper_count == len(word):
return True
# all lowercase
if upper_count == 0:
return True
# only first character uppercase
if upper_count == 1 and word[0].isupper():
return True
return False
This loop‑based approach runs in O(n) time and O(1) space as well, but it makes the underlying logic explicit, which can be helpful for learners new to string methods.
Practical Examples
To solidify understanding, let’s walk through three representative inputs and see how the function behaves.
Example 1: All Uppercase
Input: "USA"
The isupper() check scans each character, finds them all uppercase, and returns True. The function exits early, yielding True as the final result.
Output: True
Example 2: All Lowercase
Input: "aman"
The first isupper() fails because the characters are not uppercase. The second islower() succeeds, confirming that every cased character is lowercase. The function returns True.
Output: True
Example 3: Title Case
Input: "Google"
Neither isupper() nor islower() passes. The istitle() method verifies that the first character ‘G’ is uppercase and the remainder ‘oogle’ is lowercase, so it returns True.
Output: True
Now consider an invalid case such as "FlaG". Neither all‑uppercase nor all‑lowercase holds, and title case fails because the internal ‘a’ is lowercase but the final ‘G’ is uppercase, breaking the rule. Consequently, the function returns False.
Frequently Asked Questions (FAQs)
Q: What happens if the input string is empty?
A: An empty string contains no cased characters, so isupper(), islower(), and istitle() all return False. In many implementations, we treat the empty string as valid by convention because it violates none of the capitalization rules; the loop‑based version explicitly returns True for this case. If you're exploring this area, check out AI interview prep tool — Try Intervu free.
Q: Does the function consider non‑alphabetic characters?
A: Yes. The string methods ignore characters that are not cased (e.g., digits, punctuation). They only evaluate letters that have case. For example, "123" returns True because there are no cased characters, and the function treats it as valid.
Q: Can regular expressions be used instead?
A: Absolutely. A pattern like r'^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$' matches the three valid patterns. However, regex engines incur additional overhead and are less readable for this simple task, making the built‑in method approach preferable.
Q: How does the function behave with Unicode characters?
A: Python’s string methods are Unicode‑aware. They correctly identify uppercase and lowercase letters beyond ASCII, such as ‘É’ or ‘ß’. Therefore, the function works for internationalized inputs as long as the Unicode case mappings are appropriate.
Q: Is there any performance difference between the three‑if version and the one‑liner?
A: Both versions have identical asymptotic complexity. The one‑liner may be marginally faster due to fewer bytecode instructions, but the difference is negligible for typical input sizes.
Q: Could we use a list comprehension to count uppercase letters?
A: Yes, as shown in the loop‑based alternative. A comprehension like sum(1 for ch in word if ch.isupper()) provides the count in a single readable line while preserving O(n) time.
Q: Why is the order of checks important?
A: Although the logical outcome is the same regardless of order, placing the most likely pattern first can reduce average execution time. In practice, many inputs are either all lowercase or all uppercase, so checking those first yields early exits.
Q: How would you adapt this function to validate a list of words?
A: Simply iterate over the list and apply detectCapitalUse to each element, collecting the results in a new list or using a generator expression for lazy evaluation.
Conclusion
Detect Capital exemplifies how Python’s rich standard library can turn a seemingly tedious validation task into a concise, efficient solution. By mastering isupper(), islower(), and istitle(), developers can write cleaner code that is both faster and less error‑prone.
Whether you are preparing for coding interviews, building robust user‑input handling in projects like GrowthAI or Intervu, or simply seeking to deepen your Python proficiency, understanding the nuances of capitalization detection is a valuable skill.
Feel free to experiment with the alternative implementations presented here, and consider how the same principles apply to other string‑validation challenges you may encounter.
Explore more technical guides and tutorials on our articles page.