Reverse String
LeetCode 344 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 <= 10^5`
- `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
Topics: Two Pointers, String
Approachβ
Direct Approachβ
This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.
When to use
Basic problems that test fundamental programming skills.
Solutionsβ
Solution 1: C# (Best: 180 ms)β
| Metric | Value |
|---|---|
| Runtime | 180 ms |
| Memory | N/A |
| Date | 2018-04-04 |
Solution
public class Solution {
public string ReverseString(string s) {
char[] ar = s.ToCharArray();
int i=0, j=s.Length-1;
while(i<j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
i++;
j--;
}
return new string(ar);
}
}
π 2 more C# submission(s)
Submission (2022-04-01) β 360 ms, 47.9 MBβ
public class Solution {
public void ReverseString(char[] s) {
int i=0, j = s.Length-1;
while(i<j)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}
Submission (2019-12-15) β 404 ms, 35.9 MBβ
public class Solution {
public void ReverseString(char[] s) {
helper(0, s.Length-1, s);
}
public void helper(int i, int j, char[] s)
{
if(i>=j) return;
helper(i+1, j-1, s);
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Two Pointers | $O(n)$ | $O(1)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 1 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: The entire logic for reversing a string is based on using the opposite directional two-pointer approach!