Number of Segments in a String - Problem

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Note that the string may contain leading/trailing spaces or multiple spaces between segments.

Input & Output

Example 1 — Basic Case
$ Input: s = "Hello, my name is John"
Output: 5
💡 Note: The five segments are: "Hello,", "my", "name", "is", "John"
Example 2 — Multiple Spaces
$ Input: s = "Hello"
Output: 1
💡 Note: Only one segment: "Hello"
Example 3 — Leading/Trailing Spaces
$ Input: s = " Hello world "
Output: 2
💡 Note: Two segments: "Hello" and "world", ignoring leading/trailing spaces

Constraints

  • 0 ≤ s.length ≤ 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters: ' ', '.', ',', '?', '!', '"', '/', '\', '(', ')'

Visualization

Tap to expand
Number of Segments: "Hello, my name is John"Input StringHello, my name is JohnIdentified SegmentsHello,mynameisJohnSegment 1Segment 2Segment 3Segment 4Segment 5Output: 5 segments
Understanding the Visualization
1
Input
String with words separated by spaces
2
Process
Identify non-space character sequences
3
Output
Count of segments found
Key Takeaway
🎯 Key Insight: Count groups of non-space characters, ignoring multiple spaces between them
Asked in
Google 15 Amazon 12
28.5K Views
Medium Frequency
~15 min Avg. Time
856 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