Number of Segments in a String solution and explanation
9 more videos on this problem
LeetCode 434. Number of Segments in a String Solution Explained - JavaNick White · 4:54 · 5K views
434. Number of Segments in a String || LEETCODE SOLUTION || IN C++ || DATA STRUCTURE AND ALGORITHMAbhishweta Gupta · 1:22 · 806 views
LeetCode 434 | Number of Segments in a String | String | JavaSleepy Cracker · 3:22 · 524 views
LeetCode 434 : Number of Segments in a String || EASY || C++ || JAVA || Detailed SolutionCodeGPT · 6:50 · 484 views
Number of Segments in a String - Google Interview Questions - LeetCode 434 Solution - C++nexTRIE · 5:43 · 387 views
434. Number of Segments in a String | Leetcode | PythonAbdullah Arshed · 2:29 · 300 views
LeetCode 434 - Number of Segments in a String || Java SolutionV Codes · 1:13 · 290 views
Number of Segments in a String - LeetCode 434 - Java Solutionalgobest - Computer Science · 1:46 · 234 views
434. Number of Segments in a String | Java | Leetcode | Strings | FundamentalsCoding with Tamilarasan · 6:58 · 219 views
434. Number of Segments in a String - LeetCode Pair Programming in JavaScriptBecoming A Better Dev (with David) · 28:42 · 164 views
The problem
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' '.
Approach overview
Problem Overview: You receive a string that may contain words separated by one or more spaces. A segment is defined as a contiguous sequence of non-space characters. The task is to count how many such segments exist in the string.
Approach 1: Splitting Based on Spaces (O(n) time, O(n) space)
This approach uses the built-in split() function available in most languages. Splitting the string on spaces produces an array of tokens, where each token represents a potential word. Because multiple spaces can appear between words, you must filter out empty strings before counting. Internally, the runtime scans the entire string once to create substrings, which makes the time complexity O(n). The additional array of tokens requires O(n) auxiliary space.
This method is concise and readable. It works well in scripting or production environments where clarity matters more than micro-optimizations. Since the problem revolves around parsing a string, built-in splitting utilities are often the fastest way to express the solution.
Approach 2: Manual Counting with Iteration (O(n) time, O(1) space)
A more interview-focused approach scans the string character by character and counts the start of each segment. A new segment begins when the current character is not a space and either it is the first character in the string or the previous character is a space. Every time this condition appears, increment the counter. This detects transitions from space to non-space characters.
The algorithm performs a single linear pass over the string using a simple loop, giving O(n) time complexity. It only stores a counter and a few temporary variables, so the extra space is O(1). This technique is a classic pattern in string traversal problems where you detect boundaries between tokens without allocating additional data structures.
Recommended for interviews: Manual counting with iteration is typically what interviewers expect. It shows that you understand how segments are formed and can detect word boundaries during a single scan. The split-based solution demonstrates familiarity with language utilities, but the iterative approach proves stronger algorithmic reasoning and better space efficiency.
Approach 1: Splitting Based on Spaces
One efficient way to determine the number of segments in a string is to utilize its built-in split method, which divides the string into parts based on spaces. The segments will represent contiguous sequences of non-space characters. This approach handles all continuous whitespaces correctly by filtering out empty strings in the resulting list or array.
def count_segments(s: str) -> int:
return len(s.split())
s = "Hello, my name is John"
print(count_segments(s))public class Solution {
public static int countSegments(String s) {
String[] segments = s.trim().split("\\s+");
return segments[0].isEmpty() ? 0 : segments.length;
}
public static void main(String[] args) {
String s = "Hello, my name is John";
System.out.println(countSegments(s));
}
}#include <iostream>
#include <sstream>
int countSegments(const std::string &s) {
std::istringstream stream(s);
std::string segment;
int count = 0;
while (stream >> segment) {
++count;
}
return count;
}
int main() {
std::string s = "Hello, my name is John";
std::cout << countSegments(s) << std::endl;
return 0;
}function countSegments(s) {
return s.split(/\s+/).filter(Boolean).length;
}
let s = "Hello, my name is John";
console.log(countSegments(s));#include <stdio.h>
#include <string.h>
int countSegments(char *s) {
int count = 0;
char *token = strtok(s, " ");
while (token) {
count++;
token = strtok(NULL, " ");
}
return count;
}
int main() {
char str[] = "Hello, my name is John";
printf("%d\n", countSegments(str));
return 0;
}using System;
public class Solution {
public static int CountSegments(string s) {
return s.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length;
}
public static void Main(string[] args) {
string s = "Hello, my name is John";
Console.WriteLine(CountSegments(s));
}
}This Python function uses the built-in split() method with no arguments, which appropriately splits the string by any whitespace and handles multiple spaces effectively.
Time Complexity: O(n), iterating through each character. Space Complexity: O(m), for storing segments as a list.
Approach 2: Manual Counting with Iteration
This approach iteratively examines the characters of the string to manually count segments. We increment the segment count every time we encounter the start of a segment: a non-space character that was preceded by a space or the start of the string.
def count_segments(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
s = "Hello, my name is John"
print(count_segments(s))public class Solution {
public static int countSegments(String s) {
int count = 0;
boolean inSegment = false;
for (char c : s.toCharArray()) {
if (c != ' ') {
if (!inSegment) {
count++;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
public static void main(String[] args) {
String s = "Hello, my name is John";
System.out.println(countSegments(s));
}
}#include <iostream>
int countSegments(const std::string &s) {
int count = 0;
bool inSegment = false;
for (char ch : s) {
if (ch != ' ') {
if (!inSegment) {
++count;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
int main() {
std::string s = "Hello, my name is John";
std::cout << countSegments(s) << std::endl;
return 0;
}function countSegments(s) {
let count = 0;
let inSegment = false;
for (let char of s) {
if (char !== ' ') {
if (!inSegment) {
count++;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
let s = "Hello, my name is John";
console.log(countSegments(s));#include <stdio.h>
#include <stdbool.h>
int countSegments(char *s) {
int count = 0;
bool inSegment = false;
for (; *s; s++) {
if (*s != ' ') {
if (!inSegment) {
count++;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
int main() {
char str[] = "Hello, my name is John";
printf("%d\n", countSegments(str));
return 0;
}using System;
public class Solution {
public static int CountSegments(string s) {
int count = 0;
bool inSegment = false;
foreach (char c in s) {
if (c != ' ') {
if (!inSegment) {
count++;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
public static void Main(string[] args) {
string s = "Hello, my name is John";
Console.WriteLine(CountSegments(s));
}
}This Python solution uses a loop to traverse each character in the string, toggling a boolean to track whether or not the current character initiates a new segment.
Time Complexity: O(n), since each character is checked only once. Space Complexity: O(1), as only a few scalar variables are used.
Approach 3: String Splitting
We split the string s by spaces and then count the number of non-empty words.
The time complexity is O(n), and the space complexity is O(n), where n is the length of the string s.
function countSegments(s: string): number {
return s.split(/\s+/).filter(Boolean).length;
}func countSegments(s string) int {
ans := 0
for _, t := range strings.Split(s, " ") {
if len(t) > 0 {
ans++
}
}
return ans
}class Solution {
/**
* @param String $s
* @return Integer
*/
function countSegments($s) {
$arr = explode(' ', $s);
$cnt = 0;
for ($i = 0; $i < count($arr); $i++) {
if (strlen($arr[$i]) != 0) {
$cnt++;
}
}
return $cnt;
}
}Approach 4: Simulation
We can also directly traverse each character s[i] in the string. If s[i] is not a space and s[i-1] is a space or i = 0, then s[i] marks the beginning of a new word, and we increment the answer by one.
After the traversal, we return the answer.
The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).
function countSegments(s: string): number {
let ans = 0;
for (let i = 0; i < s.length; i++) {
let c = s[i];
if (c !== ' ' && (i === 0 || s[i - 1] === ' ')) {
ans++;
}
}
return ans;
}func countSegments(s string) int {
ans := 0
for i, c := range s {
if c != ' ' && (i == 0 || s[i-1] == ' ') {
ans++
}
}
return ans
}class Solution {
/**
* @param String $s
* @return Integer
*/
function countSegments($s) {
$ans = 0;
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if ($c !== ' ' && ($i === 0 || $s[$i - 1] === ' ')) {
$ans++;
}
}
return $ans;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Splitting Based on Spaces | Time Complexity: O(n), iterating through each character. Space Complexity: O(m), for storing segments as a list. |
| Manual Counting with Iteration | Time Complexity: O(n), since each character is checked only once. Space Complexity: O(1), as only a few scalar variables are used. |
| String Splitting | – |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Splitting Based on Spaces | O(n) | O(n) | Quick implementation using built-in string split utilities |
| Manual Counting with Iteration | O(n) | O(1) | Preferred in interviews or memory-constrained scenarios |
Frequently asked questions
Is Number of Segments in a String easy or hard?
Number of Segments in a String is categorized as an Easy problem. It mainly tests understanding of string traversal and boundary detection, which are foundational skills for many string manipulation questions.
Number of Segments in a String Python/Java solution
In Python, you can use s.split() and count non-empty tokens, or manually iterate through the string to detect segment starts. In Java, similar logic applies using split(" ") or a loop checking transitions from space to non-space characters.
How to solve Number of Segments in a String in O(n)?
Iterate through the string and detect the start of each word. If the current character is not a space and either it is at index 0 or the previous character is a space, increment the segment counter. This single-pass scan guarantees O(n) time and O(1) extra space.
What is the best approach for Number of Segments in a String?
The most efficient approach is manual counting with iteration. Scan the string once and increment a counter whenever a non-space character appears after a space or at the start of the string. This detects the beginning of each word segment in O(n) time and O(1) space.
Is Number of Segments in a String asked at Google/Amazon/Meta?
String parsing and token counting problems frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary in wording, the concept of scanning strings and detecting word boundaries is a common interview pattern.
What data structure is used in Number of Segments in a String?
The problem mainly relies on string traversal. The optimal approach uses only the input string and a counter variable, so no additional data structures are required. Some implementations use arrays or lists if they rely on splitting the string.
What is the time complexity of Number of Segments in a String?
The optimal solution runs in O(n) time, where n is the length of the string. The algorithm performs a single pass through the characters and checks transitions from spaces to non-space characters to identify segment boundaries.
