Magicsheet logo

Number of Segments in a String

Easy
12.5%
Updated 8/1/2025

Asked by 3 Companies

Topics

Number of Segments in a String

What is this problem about?

The Number of Segments in a String problem asks you to count the number of segments (words separated by spaces) in a given string. Segments are contiguous non-space character sequences. The challenge is handling multiple consecutive spaces correctly. This easy string problem tests clean string traversal.

Why is this asked in interviews?

Microsoft, Amazon, and Google ask this easy problem to verify clean string parsing skills. It's often used as a quick warm-up to assess whether candidates handle edge cases like leading/trailing spaces and multiple spaces between words without resorting to unnecessary string splitting. The string interview pattern is demonstrated.

Algorithmic pattern used

Single-pass transition detection. Count transitions from space to non-space. For each character, if s[i] != ' ' and either i == 0 or s[i-1] == ' ', it's the start of a new segment. Increment count.

Or alternatively: count characters where s[i] != ' ' and (i == 0 or s[i-1] == ' ').

Example explanation

s = "Hello World ". (two spaces between words, trailing spaces)

  • 'H': non-space, s[-1] is boundary → new segment. Count=1.
  • 'e','l','l','o': non-space after non-space → no new segment.
  • ' ',' ': spaces.
  • 'W': non-space after space → new segment. Count=2.
  • 'o','r','l','d': continuation.
  • ' ',' ': trailing spaces. No new segment. Result = 2.

Common mistakes candidates make

  • Using s.split() (correct but trivially skips the learning exercise).
  • Counting all non-space characters instead of segment starts.
  • Off-by-one: checking s[i-1] when i=0 causes index error.
  • Forgetting trailing spaces don't start a segment.

Interview preparation tip

"Count words/segments" problems cleanly use the transition detection pattern: new segment = current non-space AND previous is space (or start). This avoids creating a new list of tokens. Practice writing this as a one-liner: sum(1 for i, c in enumerate(s) if c != ' ' and (i == 0 or s[i-1] == ' ')). Transition detection is a reusable pattern for "count runs," "count transitions," and similar problems.

Similar Questions