We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Segments in a String

Number: 434

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a string s, count the number of segments (contiguous sequences of non-space characters) in it. For example, given "Hello, my name is John", the answer is 5.


Key Insights

  • A segment is defined as a contiguous block of non-space characters.
  • Splitting the string using spaces or iterating over the string to detect transitions from a space to a non-space character helps count segments.
  • The string may contain leading, trailing, or multiple spaces between segments.
  • Edge cases include empty strings or strings with only spaces.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) if iterating over the string, O(n) if using built-in split functions depending on implementation.


Solution

The idea is to iterate through each character of the string and identify when a new segment begins. One efficient approach is to maintain a flag indicating whether we are currently inside a segment. When a non-space character is encountered after a space, a new segment is counted.

Alternatively, a built-in method such as splitting the string by spaces and filtering out empty strings can be used. Both approaches handle multiple spaces and edge cases like empty strings.


Code Solutions

# Define a function that counts the number of segments in a string
def count_segments(s):
    # Initialize segment count and a flag indicating if we're inside a segment
    count = 0
    in_segment = False
    
    # Iterate through each character in the string
    for char in s:
        # If the character is not a space, we are in a segment
        if char != " ":
            # If we were not already in a segment, then this is the start of a new segment
            if not in_segment:
                count += 1
                in_segment = True
        else:
            # When we hit a space, mark that we are no longer in a segment
            in_segment = False
    # Return the total count
    return count

# Example usage:
print(count_segments("Hello, my name is John"))  # Output: 5
← Back to All Questions