Similar Problems

Similar Problems not available

Reverse String - Leetcode Solution

Companies:

LeetCode:  Reverse String Leetcode Solution

Difficulty: Easy

Topics: string two-pointers  

Problem Description: Given a string s, return the string reversed.

Example 1: Input: s = "hello" Output: "olleh"

Example 2: Input: s = "world" Output: "dlrow"

Approach: The idea is to swap the first and last character of the string, then move towards the middle of the string, swapping the characters on the left and right side. We can use two pointers for this.

Algorithm:

  1. Initialize two pointers, one at the start and the other at the end of the string.
  2. Swap the characters at the two pointers.
  3. Move the left pointer towards the right side of the string.
  4. Move the right pointer towards the left side of the string.
  5. Repeat the above two steps until the pointers cross each other.

Code:

class Solution { public: string reverseString(string s) { int n = s.length(); int left = 0, right = n - 1; while (left < right) { swap(s[left], s[right]); left++; right--; } return s; } };

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), as we are not using any extra memory to store characters.

Reverse String Solution Code

1