Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Detect Capital

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "520" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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.

Explanation

Here's the breakdown of the solution:

  • Analyze Cases: The problem boils down to checking three possible scenarios: all uppercase, all lowercase, or only the first letter uppercase.
  • Boolean Flags: Use boolean flags to represent whether the first character is uppercase and whether the rest of the characters are uppercase/lowercase.
  • Conditional Logic: Efficiently combine these boolean flags to determine if the word adheres to one of the valid capitalization patterns.

  • Runtime & Storage Complexity: O(n) runtime, O(1) storage

Code

    def detectCapitalUse(word: str) -> bool:
    """
    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.
    """

    n = len(word)
    first_upper = 'A' <= word[0] <= 'Z'
    all_upper_from_second = True
    all_lower_from_second = True

    for i in range(1, n):
        if 'a' <= word[i] <= 'z':
            all_upper_from_second = False
        else:
            all_lower_from_second = False

    if first_upper:
        return all_upper_from_second or all_lower_from_second
    else:
        return all_lower_from_second

More from this blog

C

Chatmagic blog

2894 posts