Number of Valid Words in a Sentence - Problem

A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.

A token is a valid word if all three of the following are true:

  • It only contains lowercase letters, hyphens, and/or punctuation (no digits).
  • There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
  • There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).

Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".

Given a string sentence, return the number of valid words in sentence.

Input & Output

Example 1 — Basic Validation
$ Input: sentence = "cat and dog"
Output: 3
💡 Note: All three words are valid: "cat" (only lowercase), "and" (only lowercase), "dog" (only lowercase). Multiple spaces between words don't affect token validation.
Example 2 — Invalid Words with Digits
$ Input: sentence = "!this 1-s b8d!"
Output: 2
💡 Note: "!this" is valid (punctuation at start, only letters after), "1-s" is invalid (contains digit), "b8d!" is invalid (contains digit). Only 2 valid words.
Example 3 — Hyphen and Punctuation Rules
$ Input: sentence = "alice and bob are playing stone-game10"
Output: 5
💡 Note: "alice", "and", "bob", "are", "playing" are all valid. "stone-game10" is invalid due to digits. Hyphen in "stone-game10" would be valid if no digits were present.

Constraints

  • 1 ≤ sentence.length ≤ 1000
  • sentence only contains lowercase English letters, digits, spaces, hyphens, and punctuation marks

Visualization

Tap to expand
Valid Words: "cat and dog"catanddog✓ No digits✓ No digits✓ No digits✓ No hyphens✓ No hyphens✓ No hyphens✓ No punctuation✓ No punctuation✓ No punctuationAll tokens pass the three validation rulesResult: 3 valid words
Understanding the Visualization
1
Input
Sentence with mixed valid/invalid tokens
2
Validation
Check each token against three rules
3
Count
Count tokens that pass all rules
Key Takeaway
🎯 Key Insight: A token is valid only if it passes ALL three checks: no digits, proper hyphen placement, proper punctuation placement
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen