Strings String basics

123. Reverse String

Easy

You are given an array of characters, s. Reverse the order of the characters. The first character becomes the last, the second becomes the second to last, and so on.

Change s itself, using only O(1) extra memory. The function returns nothing; the answer is what s holds after it finishes. Spaces and punctuation marks are characters like any other, and they move too.

The examples write the array as a string in double quotes, so s = "cat" is the array of the three characters c, a and t. The output shows s after your function returns, written the same way.

Example 1

Input: s = "stressed"

Output: "desserts"

Explanation: The first and last characters trade places, then the second and the seventh, and so on toward the middle. Read from the end, "stressed" spells "desserts".

Example 2

Input: s = "Was it a car?"

Output: "?rac a ti saW"

Explanation: The spaces and the question mark move just like the letters, and every letter keeps its case. The middle character, a space, stays where it is.

Example 3

Input: s = "level"

Output: "level"

Explanation: The word reads the same both ways, so it looks unchanged after the swaps.

Check your understanding

Work out the answer for this input before you write any code.

s = "abcd"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds printable ASCII characters only (codes 32 to 126): letters, digits, spaces and punctuation.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.