Number of Segments in a String (LeetCode 434): Solution and Explanation
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
- Set
segments = 0. - Walk every index
iofs. - If
s[i]is not a space and eitheri == 0ors[i - 1]is a space, a new segment starts: add one. - Return
segmentsafter the loop.
Step-by-step example
s = "Hello, my name is John"
Hat index 0 is not a space and has nothing before it: segment 1.e,l,l,o,,each follow a non-space, so they continue segment 1.- The space at index 6 is skipped.
mfollows it: segment 2. nof "name" follows a space: segment 3.iof "is": segment 4.Jof "John": segment 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 segments1class Solution {
2 public int countSegments(String s) {
3 int segments = 0;
4 for (int i = 0; i < s.length(); i++) {
5 if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
6 segments++;
7 }
8 }
9 return segments;
10 }
11}1class Solution {
2public:
3 int countSegments(string s) {
4 int segments = 0;
5 for (int i = 0; i < (int)s.size(); i++) {
6 if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
7 segments++;
8 }
9 }
10 return segments;
11 }
12};Time and space complexity
O(n)
Each index is checked once against itself and its left neighbour.
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]wheni == 0. Checki == 0first 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.