Reverse String
Reverse String is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the String Reversal subpattern.
Problem statement
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
Constraints:
- 1 <= s.length <= 105
- s[i] is a printable ascii character.
Topics and companies
Topics: Two Pointers, String.
Reported in interviews at Apple, Microsoft, Goldman Sachs, Amazon, Adobe, Bloomberg.
How to practise Reverse String on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n), where n is the length of the input vector. Each character is swapped at most once. time and O(1) extra space (ignoring the returned vector, which is required by the function signature). The reversal is done in-place within the local copy of the vector. space.
Open Reverse String in the code editor, or read the Reverse String editorial for a worked solution with its approach and complexity analysis.
Where Reverse String sits in the DSA pattern sheet
- Two Pointers pattern guide
- String Reversal subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Reverse String
Other problems that use the same String Reversal and Two Pointers techniques:
- Reverse String II — Easy, same subpattern
- Reverse Vowels of a String — Easy, same subpattern
- Reverse Words in a String — Medium, same subpattern
- Backspace String Compare — Easy, same pattern
- Boats to Save People — Medium, same pattern
- Container With Most Water — Medium, same pattern
Preparing your workspace
Progress is saved as you study.