Remove Spaces from a String in Java
The Remove Spaces problem is a simple string manipulation task where we are given a string s, and we need to remove all space characters ' ' while preserving the order of the remaining characters.
This is a common problem used to understand string traversal, filtering, and efficient string building techniques.
Problem Statement
Given a string s, remove all spaces and return the modified string.
Examples
Example 1
Input:
s = "g eeks for ge eks"
Output:
"geeksforgeeks"
Example 2
Input:
s = "abc d "
Output:
"abcd"
Key Idea
The approach is straightforward:
Iterate through the string character by character
Keep only non-space characters
Build a new result string
Since strings are immutable in Java, using StringBuilder is the most efficient approach.
Java Solution
class Solution {
String removeSpaces(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// keep only non-space characters
if (ch != ' ') {
sb.append(ch);
}
}
return sb.toString();
}
}
How the Code Works
Step 1: Create a Result Container
StringBuilder sb = new StringBuilder();
Step 2: Traverse the String
for (int i = 0; i < s.length(); i++)
Step 3: Filter Spaces
if (ch != ' ')
Step 4: Build Final String
return sb.toString();
Execution Example
Input:
"g eeks for ge eks"
Step-by-step processing:
g → keep
→ remove
e → keep
e → keep
k → keep
s → keep
→ remove
f → keep
o → keep
r → keep
Final Output:
geeksforgeeks
Complexity Analysis
Time Complexity: O(n)
Auxiliary Space: O(n)
Conclusion
This problem demonstrates a fundamental string processing technique. It highlights how to efficiently filter characters while maintaining order. Using StringBuilder is crucial for performance, especially when dealing with large inputs (up to 10^5 characters).