Magicsheet logo

Number of Valid Words in a Sentence

Easy
66.8%
Updated 6/1/2025

Asked by 3 Companies

Topics

Number of Valid Words in a Sentence

What is this problem about?

The Number of Valid Words in a Sentence problem gives you a sentence string. A valid token is a word that has: at most one hyphen (not at the start/end), no digits, and at most one punctuation mark (only at the end). Count valid tokens separated by spaces. This easy coding problem tests careful string token validation.

Why is this asked in interviews?

Cisco, Meta, and Oracle ask this to test systematic string validation logic. Each token must be checked against multiple conditions: no digits, at most one hyphen in a valid position, optional single punctuation at end. The string interview pattern is applied with multiple condition checks.

Algorithmic pattern used

Token validation. Split the sentence on spaces. For each non-empty token: check if any character is a digit (→ invalid). Count hyphens — if more than 1, or if a hyphen is at position 0 or n-1, invalid. Check punctuation — if any punctuation occurs at a non-last position, or if more than one punctuation exists, invalid. Count valid tokens.

Example explanation

"cat dog1 - abc- -def abc".

  • "cat": no digits, no hyphens, no punctuation. Valid ✓.
  • "dog1": has digit '1'. Invalid ✗.
  • "-": hyphen at start AND end (length 1, position 0). Invalid ✗. (Actually a single '-' is at position 0 and 0 = n-1, so invalid.)
  • "abc-": hyphen at end. Invalid ✗.
  • "-def": hyphen at start. Invalid ✗.
  • "abc": valid ✓. Count = 2.

Common mistakes candidates make

  • Not splitting by space correctly (multiple spaces create empty tokens — skip them).
  • Wrong hyphen position check (at start OR end of the token, not the sentence).
  • Forgetting that digits make a token immediately invalid.
  • Not checking that punctuation only appears at the very last position.

Interview preparation tip

Multi-condition validation problems require clear separation of each rule check. Write helper functions: has_digit(token), has_valid_hyphen(token), has_valid_punctuation(token). Testing each rule independently is cleaner than nesting multiple conditions. Practice similar string validation problems (valid email format, valid variable name, valid IP address) — they all follow the "check each rule independently" approach.

Similar Questions