Number of Segments in a String — Problem & Solution
Number of Segments in a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Number of Segments in a String is an easy coding problem on strings, asked in Amazon, Infosys and Wipro interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, Infosys, Wipro
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string s, return the number of segments in it.
A segment is a maximal run of non-space characters.
Example 1
Input: s = "Hello, my name is John"
Output: 5
Example 2
Input: s = "Hello"
Output: 1
Example 3
Input: s = " "
Output: 0
Constraints
0 <= s.length <= 60s consists of printable ASCII characters and spaces.
Hints for Number of Segments in a String
Hint 1
A segment begins at a non-space character whose predecessor is a space or the start of the string.
Hint 2
Counting those starts in one pass avoids allocating a word list.
Hint 3
Careful with a string that is all spaces, or empty — both answer 0.
How to solve Number of Segments in a String
Split on whitespace runs and count the non-empty pieces.
Approach
- Split the string on whitespace, discarding empty tokens.
- Return the number of tokens.
Why it works
A segment is a maximal run of non-space characters, which is exactly what a whitespace-run split produces.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- To avoid allocating, count characters that are non-space and whose predecessor is a space or the start.
- An empty or all-space string answers 0.
Reference solution
Python
def countSegments(s: str) -> int:
return len(s.split())Java
public static int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) count++;
}
return count;
}C++
int countSegments(string s) {
int count = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) count++;
}
return count;
}JavaScript
var countSegments = function(s) {
let count = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] !== " " && (i === 0 || s[i - 1] === " ")) count++;
}
return count;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings