Number of Segments in a String - Problem

Imagine you're a text processing software that needs to count meaningful chunks of text. Given a string s, your task is to determine how many segments it contains.

A segment is defined as a contiguous sequence of non-space characters. Think of it as counting words, but more precisely - any group of characters that aren't spaces, separated by one or more spaces.

Examples:

  • "Hello World" → 2 segments: "Hello" and "World"
  • " a b " → 2 segments: "a" and "b" (leading/trailing spaces don't matter)
  • "" → 0 segments (empty string)

Your goal is to return the total count of these segments as an integer.

Input & Output

example_1.py — Basic Case
$ Input: s = "Hello, my name is John"
Output: 5
💡 Note: The string contains 5 segments: 'Hello,', 'my', 'name', 'is', and 'John'. Each segment is separated by a single space.
example_2.py — Multiple Spaces
$ Input: s = "Hello"
Output: 1
💡 Note: The string contains only one segment: 'Hello' with no spaces.
example_3.py — Edge Case
$ Input: s = ""
Output: 0
💡 Note: An empty string contains no segments, so the result is 0.

Constraints

  • 0 ≤ s.length ≤ 300
  • s consists of lowercase and uppercase English letters, digits, or spaces ' '
  • Note: The string may contain leading or trailing spaces

Visualization

Tap to expand
Counting Text Segments = Counting Islands"Hello""World""Code"Flight Path →HeWC🏝️ Islands (Segments)🌊 Water (Spaces)123🎯 Key Insight: Count transitions from water to land!
Understanding the Visualization
1
Fly Over the Map
Start scanning the string from left to right like flying over water
2
Spot Land
When you see a non-space character after spaces, you've found a new island
3
Count Islands
Each transition from 'water' to 'land' represents a new segment to count
4
Continue Flying
Keep scanning until you've covered the entire string
Key Takeaway
🎯 Key Insight: Just like counting islands from above, we only need to count the transitions from spaces to non-space characters. Each transition marks the beginning of a new segment!
Asked in
Google 25 Microsoft 18 Amazon 15 Apple 12
28.6K Views
Medium Frequency
~8 min Avg. Time
892 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