Tutorialspoint
Problem
Solution
Submissions

Reverse a String

Certification: Basic Level Accuracy: 56.6% Submissions: 53 Points: 10

Write a C++ program that reverses a string using pointers.

Example 1
  • Input: string = "hello"
  • Output: "olleh"
  • Explanation:
    • Step 1: Initialize pointers to the start and end of the string.
    • Step 2: Swap characters at start and end positions.
    • Step 3: Move start pointer forward and end pointer backward.
    • Step 4: Repeat steps 2-3 until pointers meet in the middle.
Example 2
  • Input: string = "world"
  • Output: "dlrow"
  • Explanation:
    • Step 1: Initialize pointers to the start and end of the string.
    • Step 2: Swap characters at start and end positions.
    • Step 3: Move start pointer forward and end pointer backward.
    • Step 4: Repeat steps 2-3 until pointers meet in the middle.
Constraints
  • 1 ≤ string length ≤ 10^6
  • Use pointers to reverse the string
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(1)
StringsPointers and ReferencesCapgeminiEY
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 two pointers, one at the beginning and one at the end of the string.
  • Swap the characters at these pointers and move them towards the center.
  • Stop when the pointers meet or cross each other.

Steps to solve by this approach:

 Step 1: Define a function reverse_string that takes a character pointer as parameter.

 Step 2: Create two pointers - one pointing to the start of string, another to the end.
 Step 3: While the start pointer is less than the end pointer, swap the characters they point to.
 Step 4: Increment the start pointer and decrement the end pointer after each swap.
 Step 5: In main, declare a character array with a string value.
 Step 6: Call reverse_string with this array.
 Step 7: Print the reversed string to verify the operation.

Submitted Code :