Number of Segments in a String
EasyPrompt
Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
Example 1:
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]Example 2:
Input: s = "Hello"
Output: 1
Constraints:
0 <= s.length <= 300sconsists of lowercase and uppercase English letters, digits, or one of the following characters"!@#$%^&*()_+-=',.:".- The only space character in
sis' '.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach leverages the built-in split function available in Java's String class. The idea is to split the string by spaces and then count the number of resulting non-empty parts. It's a very direct and readable solution.
Algorithm
- Trim the leading and trailing whitespace from the input string
s. - Check if the resulting string is empty. If it is, return 0.
- Split the trimmed string by the regex
\s+which matches one or more space characters. - Return the length of the resulting array of strings.
Walkthrough
The core of this method is to first prepare the string and then use the split function.
- Trim the String: The input string
sis first trimmed usings.trim()to remove any leading or trailing whitespace. This is crucial to handle cases like" hello world ", which should result in 2 segments, not more due to leading/trailing spaces. - Handle Empty String: If the trimmed string is empty, it means the original string was either empty or contained only spaces. In this case, there are no segments, so we return 0.
- Split the String: The trimmed string is then split using a regular expression that matches one or more whitespace characters (
"\\s+"). This correctly handles multiple spaces between words. - Return Length: The number of segments is simply the length of the array returned by the
splitmethod.
class Solution { public int countSegments(String s) { // Trim leading and trailing spaces String trimmed = s.trim(); // If the string is empty after trimming, there are no segments if (trimmed.isEmpty()) { return 0; } // Split the string by one or more spaces String[] segments = trimmed.split("\\s+"); // The number of segments is the length of the resulting array return segments.length; }}Complexity
Time
O(N), where N is the length of the string. The `trim()` and `split()` operations both require iterating through the string.
Space
O(N), where N is the length of the string. The `split()` method creates a new array of strings, and the total size of these strings can be proportional to the original string's length in the worst case (e.g., 'a b c d ...').
Trade-offs
Pros
Very concise and easy to read and write.
Leverages well-tested standard library functions.
Cons
Inefficient in terms of space, as it creates an intermediate array of strings.
The overhead of regular expression processing can make it slightly slower than a manual scan for simple cases.
This approach iterates through the string character by character, counting segments without allocating extra space for substrings. It is the most efficient solution in terms of memory usage.
Algorithm
- Initialize a segment counter
countto 0. - Iterate through the string
swith an indexifrom 0 tos.length() - 1. - For each character
s.charAt(i), check if it is a non-space character. - If it is a non-space character, check if it's the start of a segment. This is true if
iis 0 or the previous characters.charAt(i-1)was a space. - If both conditions are met, increment the
count. - After the loop, return the final
count.
Walkthrough
Instead of splitting the string into an array, we can count the segments by identifying their starting points. A segment starts at a non-space character that is either at the beginning of the string or is preceded by a space.
We can implement this with a single loop and a counter.
- Initialize Counter: A variable
countis initialized to 0. - Iterate Through String: We loop through the string from the first character (
i = 0) to the last. - Identify Segment Start: Inside the loop, for each character
s.charAt(i), we check two conditions:- The current character is not a space (
s.charAt(i) != ' '). - It is the start of a new segment. This is true if it's the very first character of the string (
i == 0) OR the character before it was a space (s.charAt(i - 1) == ' ').
- The current character is not a space (
- Increment Counter: If both conditions are met, we've found the beginning of a new segment, so we increment
count. - Return Count: After the loop finishes,
countholds the total number of segments.
class Solution { public int countSegments(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { // A segment starts at a non-space character that is // either at the beginning of the string or preceded by a space. if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { count++; } } return count; }}Complexity
Time
O(N), where N is the length of the string. We perform a single pass through the string.
Space
O(1). We only use a constant amount of extra space for the counter and loop variable, regardless of the input string size.
Trade-offs
Pros
Highly efficient in terms of space (O(1) space complexity).
Generally faster than the split-based approach due to no overhead from creating new objects or using regex.
Cons
The logic is slightly more complex to write and understand compared to the one-liner
splitmethod.
Solutions
Solution
class Solution {public int countSegments(String s) { int ans = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { ++ans; } } return ans; }}class Solution {public: int countSegments(string s) { int ans = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { ++ans; } } return ans; }};class Solution: def countSegments(self, s: str) -> int: ans = 0 for i, c in enumerate(s): if c != ' ' and (i == 0 or s[i - 1] == ' '): ans += 1 return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.