Tutorialspoint
Problem
Solution
Submissions

Reverse a String

Certification: Basic Level Accuracy: 75.61% Submissions: 41 Points: 5

Write a Java program to implement the reverseString(char[] s) function, which reverses a string in-place.

Example 1
  • Input: s = ['h', 'e', 'l', 'l', 'o']
  • Output: ['o', 'l', 'l', 'e', 'h']
  • Explanation:
    • Swap 'h' and 'o'
    • Swap 'e' and 'l'
    • 'l' stays → final array is reversed
Example 2
  • Input: s = ['H', 'a', 'n', 'n', 'a', 'h']
  • Output: ['h', 'a', 'n', 'n', 'a', 'H']
  • Explanation:
    • Swap pairs until midpoint
    • Characters reversed in-place
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s[i] is a printable ascii character
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsD. E. ShawOracle
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 start and one at the end of the array
  • Swap the characters at the two pointers
  • Move the left pointer to the right and the right pointer to the left
  • Continue until the pointers meet in the middle

Steps to solve by this approach:

 Step 1: Initialize two pointers, left at the start of the array (index 0) and right at the end (index length-1).
 Step 2: While the left pointer is less than the right pointer, perform steps 3-5.
 Step 3: Swap the characters at the left and right pointers.
 Step 4: Increment the left pointer.
 Step 5: Decrement the right pointer.
 Step 6: Continue until the pointers meet in the middle or cross each other.

Submitted Code :