The problem “520. Detect Capital” on LeetCode requires us to implement a function that determines if the usage of capitals in a given word is correct. Specifically, the usage of capitals in a word is considered correct if one of the following conditions is met:
Given a single word as a string, we need to return True
if the word follows any of the above capitalization rules and False
otherwise.
To solve this problem, we can consider the following steps:
Using these conditions, we can determine whether the word’s capitalization is correct or not.
Here’s the Python code to solve this problem:
def detectCapitalUse(word: str) -> bool:
if word.isupper():
return True
if word.islower():
return True
if word[0].isupper() and word[1:].islower():
return True
return False
The time complexity of the solution is O(n), where n is the length of the given word. This is because:
isupper()
method checks each character to ensure it’s uppercase, taking O(n) time.islower()
method checks each character to ensure it’s lowercase, taking O(n) time.word[1:]
takes O(n) time to create the slice, but the combined checks still result in linear time complexity.Thus, the implementation effectively travels over the word at most three times, resulting in a time complexity of O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?