Number of Segments in a String
EasyStringssimulation
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
A segment is a maximal run of consecutive characters that are not the space character ' '.
Given a string s, return how many segments it contains. Leading, trailing, and repeated spaces do not create extra segments. Only ' ' counts as a separator; punctuation such as , or ! is part of a segment.
Examples
Input: s = "Hello, my name is John"
Output: 5
The segments are "Hello,", "my", "name", "is", "John".
Input: s = "Hello"
Output: 1
The whole string is a single segment.
Input: s = " "
Output: 0
A string of only spaces has no segments.
Constraints
- 0 <= s.length <= 300
- `s` consists of English letters, digits, spaces, and the characters `!@#$%^&*()_+-=',.:`
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.