Tutorialspoint
Problem
Solution
Submissions

Reverse String

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to reverse a string. The input string is given as an array of characters. You must do this by modifying the input array in-place with O(1) extra memory. Do not allocate extra space for another array.

You must modify the input array in-place and perform the reversal operation with constant extra memory.

Example 1
  • Input: s = ["h","e","l","l","o"]
  • Output: ["o","l","l","e","h"]
  • Explanation: We start with ["h","e","l","l","o"], swap first and last characters: ["o","e","l","l","h"], swap second and second-to-last characters: ["o","l","l","e","h"]. Third character remains in place.
Example 2
  • Input: s = ["H","a","n","n","a","h"]
  • Output: ["h","a","n","n","a","H"]
  • Explanation: We start with ["H","a","n","n","a","h"], then swap characters from the outside in: first and last, second and second-to-last, third and third-to-last.
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s[i] is a printable ASCII character
  • You must modify the array in-place with O(1) extra memory
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(1)
StringsEYArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a two-pointer approach to solve this problem
  • Initialize one pointer at the beginning of the array and another at the end
  • Swap the characters at both pointers
  • Move the left pointer one step right and the right pointer one step left
  • Continue until the pointers meet or cross each other

Steps to solve by this approach:

 Step 1: Initialize two pointers - left at the beginning (index 0) and right at the end (index sSize-1) of the array.
 Step 2: While the left pointer is less than the right pointer, perform the following steps.
 Step 3: Swap the characters at positions pointed by left and right pointers using a temporary variable.
 Step 4: Increment the left pointer by 1 (move it one step to the right).
 Step 5: Decrement the right pointer by 1 (move it one step to the left).
 Step 6: Continue this process until the pointers meet or cross each other.
 Step 7: The array is now reversed in-place using O(1) extra memory.

Submitted Code :