The Number of Segments in a String problem asks you to count the number of segments (words separated by spaces) in a given string. Segments are contiguous non-space character sequences. The challenge is handling multiple consecutive spaces correctly. This easy string problem tests clean string traversal.
Microsoft, Amazon, and Google ask this easy problem to verify clean string parsing skills. It's often used as a quick warm-up to assess whether candidates handle edge cases like leading/trailing spaces and multiple spaces between words without resorting to unnecessary string splitting. The string interview pattern is demonstrated.
Single-pass transition detection. Count transitions from space to non-space. For each character, if s[i] != ' ' and either i == 0 or s[i-1] == ' ', it's the start of a new segment. Increment count.
Or alternatively: count characters where s[i] != ' ' and (i == 0 or s[i-1] == ' ').
s = "Hello World ". (two spaces between words, trailing spaces)
s.split() (correct but trivially skips the learning exercise).s[i-1] when i=0 causes index error."Count words/segments" problems cleanly use the transition detection pattern: new segment = current non-space AND previous is space (or start). This avoids creating a new list of tokens. Practice writing this as a one-liner: sum(1 for i, c in enumerate(s) if c != ' ' and (i == 0 or s[i-1] == ' ')). Transition detection is a reusable pattern for "count runs," "count transitions," and similar problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check if All A's Appears Before All B's | Easy | Solve | |
| Detect Capital | Easy | Solve | |
| Score of a String | Easy | Solve | |
| Delete Characters to Make Fancy String | Easy | Solve | |
| Find the Original Typed String I | Easy | Solve |