00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each character is tested once against three ranges: lowercase letters, uppercase letters and digits. Kept characters are appended to a StringBuilder, so their original order is preserved.

Approaches

The loop shows every rule explicitly. The regex expresses the same rule as a pattern.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. Both approaches scan the input once and build a new string of up to n characters.

Interview Tips and Recommended Approach

  • Ask what "special" means. Should spaces stay? Should accented letters such as é stay? The answer changes the character ranges or the regex.
  • Know the regex variants. [^A-Za-z0-9 ] keeps spaces, and [^\\p{L}\\p{Nd}] keeps letters and digits from every language.
  • Avoid string concatenation in a loop. result += c creates a new string each time; use a StringBuilder.
  • Remember that the original string does not change. replaceAll() returns a new string, so you must use its return value.

Recommended Approach: StringBuilder Loop

Why: it is fast, needs no regex engine and makes the kept characters explicit, which matters when an interviewer asks for a solution without regular expressions. In everyday code, the one-line replaceAll() is a fine alternative.