Problem 2047

Abstract / Summary

Count how many words in a sentence follow specific capitalization rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2047.py

class Solution:
    def countValidWords(self, sentence: str) -> int:
        valid = 0
        tokens = sentence.split(" ")
        for t in tokens:
            if not t: # multiple spaces => empty tokens
                continue

            # no digits
            if re.search("[0-9]", t):
                continue

            # punctuation only at the end
            if t[-1] in [ "!", ".", "," ]:
                t = t[:-1]
                 # could be empty now
                if not t:
                    valid += 1
                    continue

            # no more punctuation
            if re.search("[\!\.\,]", t):
                continue

            # at most one hyphen
            if t.count("-") > 1:
                continue
            if t[0] == "-" or t[-1] == "-":
                continue

            valid += 1

        return valid
33 lines | 896 bytes | submitted October 11, 2023 | GitHub   27% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 31% (100k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method countValidWords that receives a string sentence and returns the number of tokens that satisfy a specific set of linguistic rules. The algorithm proceeds by splitting the input on spaces, discarding empty fragments that arise from consecutive spaces, and then applying a series of regular-expression checks and character inspections to decide whether each token is valid. The final count is accumulated in the variable valid and returned.

Tokenization and Early Elimination

The first logical block isolates individual words by using the built-in split method with a single space as the delimiter.

tokens = sentence.split(" ")
for t in tokens:
    if not t:  # multiple spaces => empty tokens
        continue

By checking if not t the code immediately skips any empty strings that result from multiple consecutive spaces, ensuring that only non-empty fragments are examined further. This early elimination prevents unnecessary processing of tokens that could never be valid.

Digit Exclusion

The next step removes any token that contains a numeric character. A regular expression searches for any digit, and the token is discarded if a match is found.

if re.search("[0-9]", t):
    continue

This guard guarantees that tokens with embedded numbers are never counted as valid, aligning with the rule that a valid word must be free of digits.

Handling Terminal Punctuation

The algorithm permits a single punctuation mark (!, ., or ,) at the very end of a token. If the last character belongs to this set, it is stripped off, and the remaining substring is examined.

if t[-1] in ["!", ".", ","]:
    t = t[:-1]
    # could be empty now
    if not t:
        valid += 1
        continue

When the removal of the trailing punctuation leaves an empty string, the token is considered valid (for example, a solitary punctuation mark). The count is incremented, and processing moves to the next token.

Prohibiting Internal Punctuation

After any trailing punctuation has been removed, the code ensures that no other punctuation characters appear within the token. A second regular-expression search looks for any of the three punctuation symbols anywhere in the remaining string.

if re.search("[\!\.\,]", t):
    continue

If such a character is found, the token is rejected, enforcing the rule that punctuation may appear only at the end.

Hyphen Constraints

Hyphens are allowed under strict conditions: at most one hyphen may appear, and it cannot be the first or last character of the token. The implementation checks the count of hyphens and the positions of any hyphen.

if t.count("-") > 1:
    continue
if t[0] == "-" or t[-1] == "-":
    continue

These checks guarantee that tokens like well-known pass, while -start, end-, or a-b-c are excluded.

Successful Validation

If a token survives all preceding filters, it is deemed valid, and the accumulator is incremented.

valid += 1

The loop then proceeds to the next token until all fragments have been examined.

Edge Cases Addressed

The code explicitly handles several edge conditions. Empty tokens generated by multiple spaces are ignored, preventing false positives. Tokens consisting solely of a punctuation character are accepted after the trailing-punctuation removal step, as the subsequent emptiness check adds to the count. Tokens that become empty after stripping a trailing punctuation mark are also counted as valid, reflecting the rule that a lone punctuation mark qualifies as a word. Hyphen placement is rigorously checked to avoid acceptance of tokens that start or end with a hyphen, as well as tokens containing more than one hyphen. Digits embedded anywhere in a token trigger immediate rejection, covering cases such as a1b or 123.

Performance Optimizations Observed

The implementation minimizes work by applying cheap checks early in the processing pipeline. The empty-token guard and digit-search are performed before any string slicing, reducing the number of times the more expensive regular-expression engine is invoked. Stripping of trailing punctuation occurs only when the last character matches one of the allowed symbols, avoiding unnecessary string copying for the majority of tokens. The hyphen count check uses the built-in count method, which is implemented in C and runs faster than a manual iteration. By ordering the validation steps from least to most costly, the algorithm reduces overall runtime, especially for long sentences with many tokens that fail early criteria. The use of a single accumulator variable valid avoids the overhead of building auxiliary collections, keeping memory usage low.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big sentence made of many small words all stuck together like train cars. This piece of code acts like a very careful guard standing at a gate to check each word one by one.

First, the guard takes the whole sentence and chops it into separate pieces wherever there is a space. This makes it easier to look at each word alone.

The guard then starts a checklist for every word. If a word has numbers like one, two, or three inside it, the guard says it is not allowed and skips it.

Next, the guard checks for punctuation marks like dots or commas. If there is a dot at the end, the guard takes it off to see what is left behind. However, the guard is very strict, so if a dot or a comma is hiding in the middle of a word instead of at the very end, the word is not allowed.

After that, the guard looks to see if there is a tiny hyphen inside the word. Usually, that is fine, but if there are too many hyphens, or if one is hanging off the very front or the very back of the word, the guard stops and moves on to the next one.

Whenever a word passes all of these strict tests, the guard adds a little gold star to a counter to show that this word is perfectly valid.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.59 | σ = 1.85

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
24 links | 13 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

16 solutions   October 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality