# Reverse String - Leet Code Solution

September 04, 2020

## Problem Statement

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

## Solution

Its very simple problem to solve.

• Take two index variables
• Start one from left, other from extreme end
• Start swapping their values, and move them
Left in forward, and extreme right in backward
• Repeat above untill both index variables cross each other

## Code

public void reverseString(char[] s) {
int left = 0;
int end = s.length-1;
while (left < end) {
//swap
char temp = s[left];
s[left] = s[end];
s[end] = temp;

left ++;
end --;
}
}

Its O(n)

## Similar Posts

### Check whether number is palindrome or not - Leet Code Solution

Problem Statement Determine whether an integer is a palindrome. An integer is a…

### Add two numbers(reverse order) link list Problem - Leet Code Solution

Problem Statement You are given two non-empty linked lists representing two non…

### How to prepare for your next Coding Interview

Here are some tips while preparing for your coding interviews. 1. Do study or…

### List of Sorting Algorithms

This topic is one of the most common studied. When somebody started preparation…

### Remove Duplicates from Sorted Array - Leet Code Solution

Problem Statement Given a sorted array nums, remove the duplicates in-place such…

### Magical usage of Bitwise operators - Get optimized solutions for many arithmatic problems

Introduction I will list some of the interesting usage of bitwise operators…

## Latest Posts

### Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Introduction Strapi is a backend system provides basic crud operations with…

### How to create Repository using Github Rest API, Configure Visibility and Assign a Team as Readonly

Introduction I had to create many repositories in an Github organization. I…