Skip to content
Problem 434 · LeetCode 434(opens in a new tab)

Number of Segments in a String

EasyStrings

You get a string s. A segment is a run of characters with no space in it, as long as possible. Return how many segments s has.

Spaces can appear anywhere: at the start, at the end, and several in a row. The string can also be empty.

Example 1

Input:  s = " hi  to go! "
Output: 3
Why:    the segments are hi, to and go!
2 more examples and the constraints

Example 2

Input:  s = ""
Output: 0
Why:    an empty string has no segments

Example 3

Input:  s = "solo"
Output: 1
Why:    no spaces, so the whole string is one segment

Constraints

  • 0 ≤ length of s ≤ 300
  • s holds English letters, digits, the space and the symbols !@#$%^&*()_+-=',.:
  • The space ' ' is the only whitespace character

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split on spacesO(n)
  2. Count segment startsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 300 charactersVerdict
Split on spacesO(n)
Short; builds the pieces
Count segment startsO(n)
Best; no extra memory

n = length of s.

Edge cases to test

  • Empty string. "" has no characters, so the answer is 0.
  • Only spaces. " " has no segment start: 0. In Java, split returns pieces that are all empty.
  • Spaces at the ends. " mid " is one segment; leading and trailing spaces add nothing.
  • Symbols. Punctuation like , or ! is part of a segment, not a separator.

Common mistakes

  • Counting spaces and adding 1, which breaks on leading, trailing or repeated spaces.
  • Counting every piece of split(" "), including the empty ones.
  • Treating punctuation as a separator: "go!" is one segment.

How to talk through it

  1. 1Clarify. Is space the only separator? Can the string be empty or only spaces?
  2. 2Give the split. Split on spaces and count non-empty pieces: linear, but it builds strings.
  3. 3Count starts instead. Each segment has one first character, a non-space after a space or at index 0.
  4. 4State the cost. One pass, O(n) time, O(1) memory.
  5. 5Test out loud. Try the empty string, only spaces, and double spaces between words.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?