Talentd
FleetCode
Make and follow sheets.Sign in

Detect Capital solution and explanation

EasyString5 min read56.8% acceptanceUpdated 9 Apr 2026
Detect capital | Leetcode #520Techdose · 8:59 · 8K viewsWatch on YouTube
9 more videos on this problem
  1. Detect capital | Leetcode #520Techdose · 8:59 · 8K views
  2. Detect Capital | LeetCode 520 | C++, Java, PythonKnowledge Center · 9:16 · 3K views
  3. Solving LeetCode 520 in JavaScript (Detect Capital)KA Education · 4:25 · 3K views
  4. Detect Capital | LeetCode 520 | Programming TutorialsProgramming Tutorials · 13:40 · 937 views
  5. Detect Capital | Leetcode 520 | Strings | Easy Approach #dsaLearn With Chirag · 6:52 · 490 views
  6. Leetcode 520: Detect CapitalAlgoGirl · 7:17 · 482 views
  7. Detect Capital - LeetCode 520 - Coding Interview QuestionsOne Code Man · 2:18 · 385 views
  8. Daily Leetcode #1007: Jan 02, 2023 - 520. Detect CapitalProgramming Live with Larry · 4:07 · 272 views
  9. 520. Detect Capital | LEETCODE EASYcode Explainer · 3:18 · 187 views
  10. Leetcode 520: Detect Capital – Step-by-Step SolutionMohit Chhabra · 16:20 · 161 views

The problem

We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA".
  • All letters in this word are not capitals, like "leetcode".
  • Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

Example 1:

Input: word = "USA"
Output: true

Example 2:

Input: word = "FlaG"
Output: false

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

Approach overview

Problem Overview: You receive a word and must verify whether its capitalization follows valid rules. A word is correct if all letters are uppercase ("USA"), all letters are lowercase ("leetcode"), or only the first letter is uppercase ("Google"). Any other combination should return false.

Approach 1: Check All Conditions Manually (O(n) time, O(1) space)

The most direct solution scans the string and validates capitalization patterns. First inspect the first two characters to determine the expected rule: either all letters should be uppercase or the rest should be lowercase. Then iterate through the remaining characters and verify they follow that rule. For example, if the first two letters are uppercase, every subsequent character must also be uppercase; otherwise all characters after the first must be lowercase. This approach uses simple character checks like isupper() and islower() and requires only one pass over the string.

This method works well because the capitalization rule becomes predictable after observing the first two letters. You only perform constant-time character checks while iterating once through the word. The algorithm runs in O(n) time where n is the length of the word, and uses O(1) extra space. Since the problem focuses purely on character inspection, it falls under typical string processing tasks.

Approach 2: Regular Expression Matching (O(n) time, O(1) space)

A concise alternative is to validate the word using a regular expression. The three valid patterns can be expressed as a single regex: all uppercase ([A-Z]+), all lowercase ([a-z]+), or first uppercase followed by lowercase ([A-Z][a-z]+). Combine them with an OR condition and check if the entire word matches the pattern. If the match succeeds, the capitalization is valid.

This solution is compact and expressive, especially in languages with strong regex support like Python, Java, and JavaScript. The regex engine still scans the entire string once, giving O(n) time complexity and O(1) extra space. Regex-based solutions are common in string validation problems and can also appear in tasks involving regular expression pattern matching.

Recommended for interviews: The manual condition check is usually preferred. It demonstrates that you understand the capitalization rules and can translate them into simple logic with a single pass over the string. Regex solutions are shorter but may hide the underlying reasoning. Showing the manual approach first proves problem-solving clarity, while mentioning the regex alternative demonstrates familiarity with practical string validation techniques.

Approach 1: Check All Conditions Manually

This approach manually checks each of the three conditions for correct capitalization. You can iterate through the word to verify that it either matches all caps, all lowercase, or the first letter is the only capital letter.

def detectCapitalUse(word: str) -> bool:
    capital_count = sum(1 for c in word if c.isupper())
    return (capital_count == len(word) or
            capital_count == 0 or
            (capital_count == 1 and word[0].isupper()))
class Solution {
    public boolean detectCapitalUse(String word) {
        int capCount = 0;
        for (char c : word.toCharArray()) {
            if (Character.isUpperCase(c)) {
                capCount++;
            }
        }
        return capCount == word.length() || capCount == 0 || (capCount == 1 && Character.isUpperCase(word.charAt(0)));
    }
}
#include <cctype>
#include <string>

bool detectCapitalUse(std::string word) {
    int capitalCount = 0;
    int n = word.length();
    for (char ch : word) {
        if (isupper(ch)) capitalCount++;
    }
    return capitalCount == n || capitalCount == 0 || (capitalCount == 1 && isupper(word[0]));
}
var detectCapitalUse = function(word) {
    let capitalCount = 0;
    for (let ch of word) {
        if (ch === ch.toUpperCase()) {
            capitalCount++;
        }
    }
    return capitalCount === word.length || capitalCount === 0 || (capitalCount === 1 && word[0] === word[0].toUpperCase());
};
#include <stdbool.h>
#include <ctype.h>

bool detectCapitalUse(char * word) {
    int n = strlen(word);
    int capitalCount = 0;
    for (int i = 0; i < n; i++) {
        if (isupper(word[i])) capitalCount++;
    }
    if (capitalCount == n) return true;
    if (capitalCount == 0) return true;
    if (capitalCount == 1 && isupper(word[0])) return true;
    return false;
}
public class Solution {
    public bool DetectCapitalUse(string word) {
        int capitalCount = 0;
        foreach (char c in word) {
            if (char.IsUpper(c)) {
                capitalCount++;
            }
        }
        return capitalCount == word.Length || capitalCount == 0 || (capitalCount == 1 && char.IsUpper(word[0]));
    }
}

In this Python solution, we use a generator expression to count uppercase letters. We then verify if all letters are uppercase, none, or only the first one is uppercase. If any condition is satisfied, we return true; otherwise, false.

Complexity

Time Complexity: O(n), with n as the word's length.
Space Complexity: O(1), since we do not employ additional data structures.

Try this approach in the editor

Approach 2: Regular Expression Matching

Using regular expressions, we can check for proper capitalization by defining patterns that match accepted formats: all uppercase, all lowercase, or initial capital only.

import re

def detectCapitalUse(word: str) -> bool:
    return bool(re.match(r'^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$', word))
import java.util.regex.*;

class Solution {
    public boolean detectCapitalUse(String word) {
        return word.matches("^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$");
    }
}
var detectCapitalUse = function(word) {
    return /^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$/.test(word);
};
using System.Text.RegularExpressions;

public class Solution {
    public bool DetectCapitalUse(string word) {
        return Regex.IsMatch(word, "^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$");
    }
}

In this Python solution, we apply a regular expression to match words fully capitalized, fully lowercase, or starting with one capital followed by lowercase letters. The re.match function verifies if the string fits any pattern. Return true if matched, false otherwise.

Complexity

Time Complexity: O(n), considering regex must check each letter.
Space Complexity: O(1), since regex requires negligible extra space.

Try this approach in the editor

Approach 3: Count the Number of Uppercase Letters

We can count the number of uppercase letters in the string, and then determine whether it meets the requirements of the problem based on the number of uppercase letters.

  • If the number of uppercase letters is 0 or equal to the length of the string, then return true.
  • If the number of uppercase letters is 1 and the first letter is an uppercase letter, then return true.
  • Otherwise, return false.

The time complexity is O(n), where n is the length of the string word. The space complexity is O(1).

function detectCapitalUse(word: string): boolean {
    const cnt = word.split('').reduce((acc, c) => acc + (c === c.toUpperCase() ? 1 : 0), 0);
    return cnt === 0 || cnt === word.length || (cnt === 1 && word[0] === word[0].toUpperCase());
}
func detectCapitalUse(word string) bool {
	cnt := 0
	for _, c := range word {
		if unicode.IsUpper(c) {
			cnt++
		}
	}
	return cnt == 0 || cnt == len(word) || (cnt == 1 && unicode.IsUpper(rune(word[0])))
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Check All Conditions Manually

Time Complexity: O(n), with n as the word's length.
Space Complexity: O(1), since we do not employ additional data structures.

Regular Expression Matching

Time Complexity: O(n), considering regex must check each letter.
Space Complexity: O(1), since regex requires negligible extra space.

Count the Number of Uppercase Letters–

Complexity analysis

ApproachTimeSpaceWhen to Use
Check All Conditions ManuallyO(n)O(1)Best for interviews and when you want explicit control over capitalization logic
Regular Expression MatchingO(n)O(1)Useful when regex support is available and concise pattern validation is preferred

Frequently asked questions

Is Detect Capital easy or hard?

Detect Capital is classified as an Easy problem on LeetCode. It mainly tests basic string traversal, character classification, and conditional logic rather than complex algorithms or data structures.

Detect Capital Python/Java solution

In Python or Java, you iterate through the characters and use built-in checks like isupper() and islower() to validate the rule. Another option is using a regular expression to match patterns like [A-Z]+, [a-z]+, or [A-Z][a-z]+. Both implementations run in O(n) time.

How to solve Detect Capital in O(n)?

Iterate through the string once while checking capitalization rules. Determine the expected pattern from the first two characters, then verify that every remaining character follows the rule. Each character is checked exactly once, giving O(n) time and constant space usage.

What is the best approach for Detect Capital?

The most common approach checks capitalization rules manually with a single pass through the string. By examining the first two characters, you determine whether the rest should be uppercase or lowercase and validate accordingly. This runs in O(n) time and O(1) space and is typically the approach interviewers expect.

Is Detect Capital asked at Google/Amazon/Meta?

Detect Capital is a classic easy-level string validation problem often used in early interview rounds. Similar capitalization or string validation questions appear in interviews at companies like Amazon, Google, and Meta to test basic string manipulation skills.

What data structure is used in Detect Capital?

The problem mainly uses simple string traversal and character checks. No additional data structures such as arrays, hash maps, or stacks are required, making it a straightforward string-processing problem.

What is the time complexity of Detect Capital?

The standard solution scans the word once and performs constant-time checks on each character. This results in O(n) time complexity where n is the length of the word, and O(1) space since no additional data structures are required.

Comments

Now write it yourselfClose this page and solve Detect Capital in the editor, without looking.
Practise Detect Capital