Number of Segments in a String (LeetCode 434): Solution and Explanation

Easy
String

Count the maximal runs of non-space characters in s. For "Hello, my name is John" the answer is 5. Spaces can repeat and can lead or trail, and s may be empty.

Intuition

Splitting on spaces works in some languages, but splitting on a single space produces empty pieces when spaces repeat or the string starts with one.

Instead, notice that every segment has exactly one first character, so counting first characters counts segments.

A character is the first of its segment when it is not a space and the character before it is a space, or there is no character before it.

Approach: Count left edges

  1. Set segments = 0.
  2. Walk every index i of s.
  3. If s[i] is not a space and either i == 0 or s[i - 1] is a space, a new segment starts: add one.
  4. Return segments after the loop.

Step-by-step example

s = "Hello, my name is John"
  1. H at index 0 is not a space and has nothing before it: segment 1.
  2. e, l, l, o, , each follow a non-space, so they continue segment 1.
  3. The space at index 6 is skipped. m follows it: segment 2.
  4. n of "name" follows a space: segment 3. i of "is": segment 4. J of "John": segment 5.
  5. The scan ends with 5.

Code: Python, Java, C++

1class Solution:
2    def countSegments(self, s: str) -> int:
3        segments = 0
4        for i in range(len(s)):
5            if s[i] != ' ' and (i == 0 or s[i - 1] == ' '):
6                segments += 1
7        return segments
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is checked once against itself and its left neighbour.

Space

O(1)

Only the counter is stored.

Other approaches

Split on whitespace runs (time O(n), space O(n))

Python's len(s.split()) or Java's s.trim().split("\\s+") with a check for the empty string. Short, but it builds every piece and the edge cases differ between languages.

In-segment flag (time O(n), space O(1))

Keep a boolean inSegment. On a non-space while the flag is false, count and set it; on a space, clear it. It is the same edge detection with state instead of a look-back.

Common mistakes

  • Counting spaces and adding one. That breaks on repeated, leading or trailing spaces and on a string of only spaces.
  • Splitting on a single space in Java or JavaScript, which keeps empty strings between consecutive spaces.
  • Reading s[i - 1] when i == 0. Check i == 0 first so the look-back never runs off the start.

Frequently asked questions

What does the function return for an empty string?

0. The loop never runs, so no left edge is found.

Do punctuation marks count as part of a segment?

Yes. Only the space character separates segments, so Hello, is a single segment.

Why look at the previous character rather than the next one?

Either works. Looking left counts first characters, looking right (a non-space followed by a space or the end) counts last characters. Each segment has exactly one of each.