https://leetcode.com/problems/detect-capital

We can solve this problem in oneline, if we use python functionality: functions isupper() islower() and istitle(). I think the first two ones are pretty classical and a lot of people aware of them (if not, it is very easy to write this function, just check if symbol is between a and z for islower() and from A to Z for isupper()). Howerer the third one is a bit cheating, so I decided not to use it.

So, we can have three cases. Let us evaluate number of capital letters first:

  1. If number of capital letters is equal to 0, then we return True.
  2. If number of capital letters is equal to n - number of all letters, we also return True.
  3. If number of capital letters is equal to 1 and first letter is capital, we return True.
  4. If none of 3 conditions above fulfilled, we return False.

Complexity: time complexity is O(n), because we traverse our string once. Space complexity is O(1), because we have only couple of additional constants.

class Solution:
    def detectCapitalUse(self, word):
        Num_cap, n = 0, len(word)
        for letter in word: 
            Num_cap += letter.isupper()
        if Num_cap == 0 or Num_cap == n or Num_cap == 1 and word[0].isupper():
            return True
        return False

If you like the solution, you can upvote it on leetcode discussion section: Problem 0520