889415. Remove all occurrences of a character in a string

Easy

Remove all occurrences of a character in a string

Summary

The problem is to remove all occurrences of a specific character from a given string. This involves iterating over the input string, identifying and removing instances of the target character.

Detailed Explanation

To solve this problem, we can iterate through the input string using a for loop or equivalent. For each character in the string, we check if it matches our target character. If it does, we remove it from the string. We can use various methods to achieve this, such as replacing the target character with an empty string, or manually manipulating the characters.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the modified input string.
  2. Iterate through each character char in the input string.
  3. Check if char matches our target character (e.g., using the equality operator).
  4. If it does, append the remaining characters up to the current index to result.
  5. Remove the matched character from the original string by skipping it during iteration.
  6. Repeat steps 2-5 until all characters have been processed.
  7. Return the modified result string.

Time complexity: O(n), where n is the length of the input string, as we iterate through each character once. Space complexity: O(1), since we only use a constant amount of space to store our result and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public String removeCharacter(String str, char c) {
    StringBuilder result = new StringBuilder();
    for (char ch : str.toCharArray()) {
        if (ch != c) {
            result.append(ch);
        }
    }
    return result.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.