LeetCode 520: Detect Capital Solution in Python – A Step-by-Step Guide

Imagine you’re a grammar detective, handed a word like “USA” or “Google,” and your mission is to determine if its capitalization is proper—either all uppercase, all lowercase, or just the first letter capitalized. That’s the neat challenge of LeetCode 520: Detect Capital, an easy-level problem that’s a fantastic way to practice string manipulation in Python. We’ll explore two solutions: the Best Solution, a single-pass character check that’s fast and straightforward, and an Alternative Solution, a regular expression approach that’s concise but less intuitive for beginners. With detailed examples, clear code, and a friendly tone—especially for the character check—this guide will help you crack the capitalization case, whether you’re new to coding or brushing up. Let’s put on our detective hats and start investigating!

What Is LeetCode 520: Detect Capital?

In LeetCode 520: Detect Capital, you’re given a string word, and your task is to return True if its capitalization follows one of three rules: all letters are capitals (e.g., “USA”), all letters are lowercase (e.g., “leetcode”), or only the first letter is capitalized (e.g., “Google”). Otherwise, return False. For example, “FlaG” is invalid. This problem tests string handling, related to LeetCode 125: Valid Palindrome for string validation.

Problem Statement

  • Input: String word.
  • Output: Boolean—True if capitalization is valid, False otherwise.
  • Rules: Valid if all caps, all lowercase, or first letter cap only.

Constraints

  • 1 <= word.length <= 100
  • word contains only English letters (uppercase or lowercase).

Examples

  • Input: "USA"
    • Output: True
    • All capitals.
  • Input: "FlaG"
    • Output: False
    • Mixed capitals invalid.
  • Input: "leetcode"
    • Output: True
    • All lowercase.
  • Input: "Google"
    • Output: True
    • First letter capitalized.

Understanding the Problem: Cracking the Capital Code

To solve LeetCode 520: Detect Capital in Python, we need a function that checks a word against three capitalization rules. A naive approach might count capitals and compare, but we can do better with a single pass or pattern matching. We’ll explore:

  • Best Solution (Single-Pass Character Check): O(n) time, O(1) space—fast and simple.
  • Alternative Solution (Regular Expression): O(n) time, O(1) space—short but regex-heavy.

Let’s dive into the single-pass solution with a friendly breakdown!

Best Solution: Single-Pass Character Check

Why Single-Pass Wins

The single-pass character check is the best for LeetCode 520 because it’s efficient, running in O(n) time with O(1) space, and easy to understand. It examines each character once, tracking the number of capitals or their positions to validate the rules. It’s like reading a word letter-by-letter with a simple checklist!

How It Works

Think of this as a capitalization checklist:

  • Step 1: Count Capitals:
    • Count uppercase letters in the word.
  • Step 2: Validate Rules:
    • All caps: Count = length.
    • All lowercase: Count = 0.
    • First cap only: Count = 1 and first letter is capital.
  • Step 3: Return:
    • True if any rule matches, False otherwise.
  • Why It Works:
    • Single pass checks all conditions.
    • No extra storage needed.

It’s like a capitalization rulebook!

Step-by-Step Example

Example: "Google"

  • Init: n = 6, caps = 0.
  • Step 1: Count capitals:
    • ‘G’: caps = 1.
    • ‘o’: caps = 1.
    • ‘o’: caps = 1.
    • ‘g’: caps = 1.
    • ‘l’: caps = 1.
    • ‘e’: caps = 1.
  • Step 2: Check rules:
    • All caps: 1 ≠ 6, False.
    • All lowercase: 1 ≠ 0, False.
    • First cap: caps = 1 and word[0] = 'G' (capital), True.
  • Result: True.

Example: "FlaG"

  • Caps: ‘F’ (1), ‘l’ (1), ‘a’ (1), ‘G’ (2).
  • Rules:
    • All caps: 2 ≠ 4, False.
    • All lowercase: 2 ≠ 0, False.
    • First cap: 2 ≠ 1, False.
  • Result: False.

Code with Detailed Line-by-Line Explanation

Here’s the Python code, explained for beginners:

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        # Step 1: Count capitals
        caps = sum(1 for char in word if char.isupper())
        n = len(word)

        # Step 2: Check the three rules
        # Rule 1: All capitals
        if caps == n:
            return True

        # Rule 2: All lowercase
        if caps == 0:
            return True

        # Rule 3: Only first letter capitalized
        if caps == 1 and word[0].isupper():
            return True

        # Step 3: If none match, invalid
        return False
  • Line 4: Count uppercase letters using isupper().
  • Line 5: Get word length.
  • Lines 8-9: All caps: caps equals length.
  • Lines 12-13: All lowercase: No caps.
  • Lines 16-17: First cap: One cap and first letter is upper.
  • Line 20: Default to False if no rule fits.
  • Time Complexity: O(n)—single pass through string.
  • Space Complexity: O(1)—just a counter.

It’s like a capitalization detective tool!

Alternative Solution: Regular Expression Approach

Why an Alternative Approach?

The regular expression (regex) solution uses pattern matching to check the rules in a concise way. It’s O(n) time and O(1) space—short and powerful but requires regex knowledge, making it less beginner-friendly. Great for regex enthusiasts!

How It Works

Picture this as a pattern-matching shortcut:

  • Step 1: Define regex pattern:
    • ^[A-Z]+$ (all caps) OR ^[a-z]+$ (all lowercase) OR ^[A-Z][a-z]*$ (first cap).
  • Step 2: Match the word against the pattern.
  • Step 3: Return True if matches, False otherwise.

It’s like a capitalization regex filter!

Step-by-Step Example

Example: "USA"

  • Pattern: ^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$.
  • Check:
    • ^[A-Z]+$: Matches “USA” (all caps), True.
  • Result: True.

Example: "FlaG"

  • Check:
    • ^[A-Z]+$: No (not all caps).
    • ^[a-z]+$: No (not all lowercase).
    • ^[A-Z][a-z]*$: No (‘G’ is capital after lowercase).
  • Result: False.

Code for Regex Approach

import re

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        # Step 1: Define regex pattern
        pattern = r'^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$'

        # Step 2: Check if word matches pattern
        return bool(re.match(pattern, word))
  • Line 5: Regex:
    • ^[A-Z]+$: All uppercase.
    • ^[a-z]+$: All lowercase.
    • ^[A-Z][a-z]*$: First cap, rest lowercase.
  • Line 8: re.match checks from start, returns match object or None.
  • Time Complexity: O(n)—regex scan.
  • Space Complexity: O(1)—fixed pattern.

It’s a regex capitalization checker!

Comparing the Two Solutions

  • Single-Pass (Best):
    • Pros: O(n), O(1), clear logic.
    • Cons: Slightly longer code.
  • Regex (Alternative):
    • Pros: O(n), O(1), concise.
    • Cons: Regex learning curve.

Single-pass wins for clarity!

Additional Examples and Edge Cases

  • ** "a": True (all lowercase).
  • ** "A": True (all caps or first cap).
  • ** "mIx": False (mixed caps).

Single-pass handles them all!

Complexity Recap

  • Single-Pass: Time O(n), Space O(1).
  • Regex: Time O(n), Space O(1).

Single-pass is the beginner’s champ!

Key Takeaways

  • Single-Pass: Simple checks win—learn at Python Basics!
  • Regex: Pattern power.
  • Strings: Caps are fun.
  • Python: Built-ins or regex, your pick!

Final Thoughts: Crack the Capital Case!

LeetCode 520: Detect Capital in Python is a delightful string challenge. The single-pass check is your fast track, while regex offers a slick alternative. Want more? Try LeetCode 125: Valid Palindrome or LeetCode 344: Reverse String. Ready to detect? Head to Solve LeetCode 520 on LeetCode and validate those capitals today!