00:00

Problem Statement

Input/Output Examples

Visual Explanation

A string of length n needs only n / 2 swaps, because each swap puts two characters in their final places.

Approaches

Both approaches return a new reversed string. The first swaps characters in a copy of the string; the second reads the string backwards.

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

Both approaches visit each character once and build one new string of length n. The two-pointer loop runs only n / 2 times, but each iteration moves two characters.

Interview Tips and Recommended Approach

  • Say that strings are immutable; any reversal builds a new string.
  • Avoid string concatenation in a loop. It is O(n2) because every + copies the whole string.
  • Mention surrogate pairs. Emoji take two chars; reversing them separately breaks them, while StringBuilder.reverse() keeps them together.
  • Handle null by agreeing a rule first: return null or throw an exception.

Recommended Approach: Two Pointers on a char Array

Why: it shows the two-pointer technique, does only n / 2 swaps and is the same pattern used in many later array and string problems.