Removing a Character from a String

What method can be used to pick or remove any given character from a string?

šŸ’”Strategies for Solving This Problem

String Manipulation Basics

Simple problem that tests your understanding of strings and efficiency. Got this at Apple in 2023 as a warmup question.

The Problem

Remove all occurrences of a character from a string. For example, remove all 'a' from "banana" → "bnn".

Naive Approach: String Concatenation

Loop through string, build new string by concatenating characters that aren't the target.

Works but in languages where strings are immutable (like Java), each concatenation creates a new string object. O(n²) time.

Better: StringBuilder / Array

Use a mutable data structure. In Java, StringBuilder. In Python, list then join. In JavaScript, array then join.

O(n) time, O(n) space.

In-Place (For Mutable Strings)

If string is mutable (like char array in C), use two pointers:

  • Read pointer scans forward
  • Write pointer tracks where to write next keeper character
  • Overwrite array in place

O(n) time, O(1) space.

Built-In Methods

Most languages have built-ins: str.replace() in JavaScript, str.replace() in Python.

Know these exist, but interviewer usually wants you to implement it yourself.

At Apple

Started with naive approach. Interviewer asked "What if the string is a million characters long?" That's when I switched to array-based solution.

Then asked: "Remove multiple characters?" Pass a set of chars to remove instead of single char.

Scroll to Top