00:00

Problem Statement

Input/Output Examples

Visual Explanation

A single comparison per character decides whether it is copied. Because the kept characters are appended in reading order, the result keeps the original order.

Approaches

The loop shows the logic explicitly. String.replace() does the same in one call.

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 read every character once and build a new string of at most n characters.

Interview Tips and Recommended Approach

  • Know the difference between replace() and replaceAll(). Only replaceAll() uses regex; removing '.' with it would remove every character.
  • Avoid deleteCharAt() in a forward loop. Deleting shifts the following characters, so the loop index skips one; loop backwards if you must delete in place.
  • Clarify case sensitivity. To ignore case, compare with Character.toLowerCase() on both sides.
  • Remember immutability. The original string is unchanged; you must use the returned value.

Recommended Approach: StringBuilder Loop

Why: it is linear, has no regex pitfalls and makes the comparison rule visible, which helps when the interviewer changes the requirements.