DDSA Solutions

Remove Spaces

Time: O(n)
Space: O(n)
Advertisement

Intuition

Remove leading, trailing, and extra spaces from string, keeping single space between words.

Algorithm

  1. 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();
    }
}
Advertisement
Was this solution helpful?