Remove Spaces
JavaView on GFG
Time: O(n)
Space: O(n)
Problem Overview
Remove leading, trailing, and extra spaces from string, keeping single space between words.
See our study guide for structured GFG and LeetCode practice.
Intuition
Remove leading, trailing, and extra spaces from string, keeping single space between words.
Algorithm
- 1Split by spaces, filter empty tokens, rejoin with single space.
Common Pitfalls
- • Same as LC 151. Or manual two-pointer scan. Handle multiple consecutive spaces and leading/trailing.
Remove Spaces.java
Java
// Approach: Iterate over the string and append each non-space character to a StringBuilder.
// Time: O(n) Space: O(n)
class Solution {
String removeSpaces(String s) {
StringBuilder sb = new StringBuilder("");
int n = s.length();
for (int i = 0; i < n; i++) {
if (s.charAt(i) != ' ') {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
Was this solution helpful?