#520

Detect Capital

Easy
StringString ManipulationCharacter Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution directly checks the conditions for valid capital usage without counting characters multiple times. This approach is more efficient as it only requires a single pass through the string.

⚙️

Algorithm

2 steps
  1. 1Step 1: If the first character is lowercase, check if all characters are lowercase.
  2. 2Step 2: If the first character is uppercase, check if all characters are uppercase or if only the first character is uppercase.
solution.py4 lines
1def detectCapitalUse(word):
2    if word[0].islower():
3        return word.islower()
4    return word.isupper() or (word[1:].islower())

Complexity note: The time complexity is O(n) because we only pass through the string once to check the conditions. The space complexity is O(1) since we use a constant amount of space.

  • 1Understanding the conditions for capital usage is crucial.
  • 2Single-pass checks are more efficient than counting characters.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.