00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each space grows the string by two characters. Counting the spaces first gives the exact output length, which is how the char[] version allocates its array once.

Approaches

The first approach appends to a builder. The second sizes an array exactly and fills it from the end.

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 input. Both approaches read every character once and produce an output of length n + 2s, where s is the number of spaces.

Interview Tips and Recommended Approach

  • Explain why to fill from the end. If the array already contains the text with spare room at the back, writing from the front would overwrite characters you have not read yet.
  • Write the three characters in reverse order when going backwards: '0', then '2', then '%'.
  • Avoid string concatenation in the loop. result += "%20" creates a new string each time.
  • Mention real URL encoding. URLEncoder.encode() handles every special character, but it turns spaces into +, not %20.

Recommended Approach: StringBuilder Loop

Why: it is clear, linear and needs no index arithmetic. In an interview, mention the backward-filling version when the question is about an in-place buffer.