Facebook Pixel

434. Number of Segments in a String

EasyString
Leetcode Link

Problem Description

You are given a string s that may contain spaces and other characters. Your task is to count how many segments are in the string.

A segment is defined as a continuous sequence of characters that are not spaces. In other words, segments are groups of non-space characters that are separated by one or more spaces.

For example:

  • In the string "Hello, my name is John", there are 5 segments: "Hello,", "my", "name", "is", and "John"
  • In the string "Hello", there is 1 segment: "Hello"
  • In the string " " (only spaces), there are 0 segments
  • In the string "" (empty string), there are 0 segments

The solution uses Python's built-in split() method, which automatically splits the string by whitespace and returns a list of non-empty segments. The len() function then counts how many segments were found. When split() is called without arguments, it handles multiple consecutive spaces correctly and ignores leading/trailing spaces.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

When we need to count segments (groups of non-space characters), we're essentially looking for word boundaries in the string. The key observation is that segments are naturally separated by spaces - wherever there's a space, it marks the end of one segment and potentially the beginning of another.

Instead of manually iterating through the string and tracking when we enter and exit segments, we can leverage the fact that this is exactly what string splitting does. When we split a string by spaces, we get individual segments as separate elements.

The built-in split() method in Python is particularly useful here because:

  1. It automatically handles multiple consecutive spaces (treats them as a single separator)
  2. It ignores leading and trailing spaces
  3. It returns only non-empty segments

This means if we have a string like " Hello World ", calling split() gives us ["Hello", "World"] - exactly the segments we want to count. The length of this list directly gives us the number of segments.

This approach transforms the problem from "count segments while handling edge cases" to simply "split and count", making the solution both elegant and efficient in a single line: len(s.split()).

Solution Approach

The implementation uses string splitting to count segments efficiently.

String Splitting Method

The solution leverages Python's built-in split() method to solve this problem in one line:

def countSegments(self, s: str) -> int:
    return len(s.split())

Here's how the implementation works:

  1. Call s.split(): When split() is called without any arguments, it splits the string by any whitespace characters (spaces, tabs, newlines, etc.). This operation automatically:

    • Removes all leading whitespace
    • Removes all trailing whitespace
    • Treats consecutive whitespace characters as a single separator
    • Returns a list containing only the non-empty segments
  2. Count with len(): Once we have the list of segments, we simply use len() to count how many elements are in the list, which gives us the number of segments.

Example Walkthrough

Let's trace through an example with s = " Hello World ":

  1. s.split() processes the string:

    • Skips the leading spaces " "
    • Finds "Hello" as the first segment
    • Skips the multiple spaces " "
    • Finds "World" as the second segment
    • Skips the trailing spaces " "
    • Returns ["Hello", "World"]
  2. len(["Hello", "World"]) returns 2

This approach handles all edge cases naturally:

  • Empty string ""split() returns [] → length is 0
  • Only spaces " "split() returns [] → length is 0
  • Single word "Hello"split() returns ["Hello"] → length is 1

The time complexity is O(n) where n is the length of the string, as we need to scan through the entire string once. The space complexity is also O(n) in the worst case to store the list of segments.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with a concrete example: s = " foo bar baz "

Step 1: Apply split() to the string

When we call s.split() on our string " foo bar baz ", Python's split method:

  • Skips the initial 2 spaces at the beginning
  • Identifies "foo" as the first segment (ends when it hits the spaces)
  • Skips the 3 spaces between "foo" and "bar"
  • Identifies "bar" as the second segment (ends at the single space)
  • Identifies "baz" as the third segment (ends when it hits the trailing spaces)
  • Skips the 2 trailing spaces at the end

This produces the list: ["foo", "bar", "baz"]

Step 2: Count the segments with len()

We apply len() to our list:

  • len(["foo", "bar", "baz"]) returns 3

Result: 3 segments

Let's verify with another quick example where edge cases come into play:

  • Input: " " (only spaces)
  • split() returns: [] (empty list, no segments found)
  • len([]) returns: 0
  • Result: 0 segments ✓

The beauty of this approach is that split() handles all the complexity of identifying segment boundaries, consecutive spaces, and edge cases, allowing us to solve the problem with just return len(s.split()).

Solution Implementation

1class Solution:
2    def countSegments(self, s: str) -> int:
3        """
4        Count the number of segments in a string.
5        A segment is defined as a contiguous sequence of non-space characters.
6      
7        Args:
8            s: Input string that may contain spaces and other characters
9          
10        Returns:
11            Number of segments (words) in the string
12        """
13        # Split the string by whitespace and count the resulting segments
14        # The split() method without arguments splits on any whitespace 
15        # and automatically removes empty strings from the result
16        return len(s.split())
17
1class Solution {
2    /**
3     * Counts the number of segments in a string.
4     * A segment is defined as a contiguous sequence of non-space characters.
5     * 
6     * @param s the input string
7     * @return the number of segments in the string
8     */
9    public int countSegments(String s) {
10        // Initialize counter for segments
11        int segmentCount = 0;
12      
13        // Split the string by space delimiter
14        String[] tokens = s.split(" ");
15      
16        // Iterate through each token
17        for (String token : tokens) {
18            // Check if token is not empty (handles consecutive spaces)
19            if (!token.isEmpty()) {
20                segmentCount++;
21            }
22        }
23      
24        return segmentCount;
25    }
26}
27
1class Solution {
2public:
3    int countSegments(string s) {
4        int segmentCount = 0;
5      
6        // Create a string stream to parse the input string
7        // The stream will automatically handle whitespace separation
8        istringstream stringStream(s);
9      
10        // Extract each word/segment from the stream
11        // The >> operator skips leading whitespace and reads until the next whitespace
12        string word;
13        while (stringStream >> word) {
14            segmentCount++;
15        }
16      
17        return segmentCount;
18    }
19};
20
1/**
2 * Counts the number of segments in a string.
3 * A segment is defined as a contiguous sequence of non-space characters.
4 * 
5 * @param s - The input string to count segments from
6 * @returns The number of segments in the string
7 */
8function countSegments(s: string): number {
9    // Split the string by one or more whitespace characters
10    // Filter out empty strings to get only non-empty segments
11    // Return the count of segments
12    return s.split(/\s+/).filter(Boolean).length;
13}
14

Time and Space Complexity

The time complexity is O(n), where n is the length of the string s. The split() method needs to traverse the entire string once to identify word boundaries (spaces) and create segments, which requires linear time proportional to the string length.

The space complexity is O(n), where n is the length of the string s. The split() method creates a new list containing all the segments (words) from the string. In the worst case, if the string contains no spaces, the entire string becomes one segment that requires O(n) space. Even with multiple segments, the total characters stored across all segments plus the list overhead can be proportional to the original string length.

Common Pitfalls

Pitfall 1: Manually Implementing with Incorrect Space Handling

A common mistake is trying to manually count segments by iterating through the string and incorrectly handling consecutive spaces or edge cases:

Incorrect Implementation:

def countSegments(self, s: str) -> int:
    count = 0
    for i in range(len(s)):
        if s[i] != ' ':
            count += 1
    return count

This counts individual characters instead of segments! It would return 20 for "Hello, my name is John" instead of 5.

Another Incorrect Attempt:

def countSegments(self, s: str) -> int:
    count = 0
    for i in range(len(s)):
        if s[i] != ' ' and (i == 0 or s[i-1] == ' '):
            count += 1
    return count

While this is closer, it still has issues with edge cases like empty strings or strings with only spaces.

Correct Manual Implementation:

def countSegments(self, s: str) -> int:
    count = 0
    in_segment = False
  
    for char in s:
        if char != ' ':
            if not in_segment:
                count += 1
                in_segment = True
        else:
            in_segment = False
  
    return count

Pitfall 2: Using split(' ') Instead of split()

Using split(' ') with a space argument creates different behavior than split() without arguments:

Incorrect:

def countSegments(self, s: str) -> int:
    return len(s.split(' '))

This fails for:

  • Multiple consecutive spaces: "Hello World" would produce ['Hello', '', 'World'], counting empty strings
  • Leading/trailing spaces: " Hello" would produce ['', 'Hello']

To fix this with split(' '), you'd need to filter out empty strings:

def countSegments(self, s: str) -> int:
    return len([segment for segment in s.split(' ') if segment])

Pitfall 3: Not Considering All Whitespace Types

If the problem specification includes other whitespace characters (tabs, newlines), manually checking only for spaces ' ' would miss segments:

Potentially Incorrect for Extended Whitespace:

def countSegments(self, s: str) -> int:
    # Only checks for space character, not tabs or newlines
    segments = s.strip().split(' ')
    return len([seg for seg in segments if seg])

The beauty of using split() without arguments is that it handles all whitespace types automatically, making it the most robust solution.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which of the two traversal algorithms (BFS and DFS) can be used to find whether two nodes are connected?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More