Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Reversing a String in Place
ab
ab

Posted on

     

Reversing a String in Place

Today's algorithm of the day is theReverse String problem:

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.

This kind of problem (and variations on it) pop up all the time, so knowing how to modify an array in place is a super useful skill.

Today, I'm going to be solving this problem with two pointers--one at each end of the array--and "swapping" the letters at those spots. I'll start by going over the approach I'll be taking, and then I'll code out the solution using JavaScript.

Approaching this Problem

The idea behind a two pointer solution is to have a pointer at each end of a word (or array), to swap the letters at those points, and to keep moving the two pointers toward the middle of the word. By the time the pointers meet in the middle, the word will be reversed.

To better explain this idea, I'll use an example. We'll start with the word "TANDEM", and two pointers. The left pointer is at start, the "T", and the right pointer is at the end, the "M".

Each letter of

Now, we'll want to swap these two letters: "T" will go in the "M" spot, and "M" will go in the "T" spot. After swapping, we get the string "MANDET".

First there is the same word in the blocks from before. A blue arrow from the left letter pointing to the right letter, and a red arrow from right letter pointing to the left letter. Below that is the result of swapping those letters:

Now we can move our pointers toward the center. The left pointer is now on the "A", and the right pointer is on the "E". We will swap these letters, putting the "A" where the "E" was, and the "E" where the "A" was. After swapping, we get "MENDAT".

Blue left arrow pointing to the

Again we move the pointers toward the center. The left pointer is on "N", and the right pointer is on "D". We'll swap these letters, and we have "MEDNAT", which is "TANDEM" backwards.

Blue left arrow points to the

We know to stop because we always want the left pointer to be to the left of the right pointer. In other words, we'll want the process to keep going until the pointers meet at the middle.

Coding the Solution

Now that we've walked through how this solution would work, we can move onto coding it. To start, we'll want to make the pointers,left andright. We'll setleft equal to 0, so that it starts at the beginning, and we'll setright equal to the length of the string minus 1, so that it starts at the end of the string (remember that indexing starts at 0).

functionreverseString(str){letleft=0;letright=str.length-1;//...}
Enter fullscreen modeExit fullscreen mode

We'll want to keep doing something until left and right meet at the middle, which means this is a good time to use a while loop. As long asleft is less thanright (aka to the left of right), we'll want to be swapping the letters.

functionreverseString(str){letleft=0;letright=str.length-1;while(left<right){//...}}
Enter fullscreen modeExit fullscreen mode

To do the swapping, we'll need to create two variables, which will both temporarily store the values at each index. We need these temporary variables or else the swapping couldn't work. To see why, let's briefly look at the example of "CAT". If we wanted to reverse this string, anddidn't use temporary variables, we'd do something like

//...str[left] = str[right] // right now, str = "TAT"str[right] = str[left] // again, str = "TAT"//...
Enter fullscreen modeExit fullscreen mode

Without temporary variables, therefore, we wouldn't have a way of "remembering" which variable used to be at the index.

So, we'll createtempStart andtempEnd.tempStart will store the variable at theleft index, andtempEnd will store the variable at theright index.

functionreverseString(str){letleft=0;letright=str.length-1;while(left<right){consttempStart=str[left];consttempEnd=str[right];//...}}
Enter fullscreen modeExit fullscreen mode

Now that the values are stored in these temporary variables, we can go ahead and swap them. We'll set the value at the left pointer equal totempEnd, and the value at the right pointer equal totempStart. And finally, we'll move the pointers--left will increment, and right will decrement, so that they both go toward the center.

functionreverseString(str){letleft=0;letright=str.length-1;while(left<right){consttempStart=str[left];consttempEnd=str[right];str[left]=tempEnd;str[right]=tempStart;left++;right--;}}
Enter fullscreen modeExit fullscreen mode

This two pointer iterative approach is done in constant space (O(1)) and linear time (O(n)).

As always, let me know in the comments if you have any questions or ideas!

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nightoutcoderatgit profile image
noc@dev
  • Joined
• Edited on• Edited

@alisabaj , If we go with only one variable inside while, is there any problem.?

looks ok to me.

function reverseString(str) {    let left = 0;    let right = str.length - 1;    while (left < right) {      const temp = str[left];      str[left] = str[right];      str[right] = temp;      left++;      right--;    }  }
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
__5fb02e7 profile image
Роман Барахвостов
  • Joined
• Edited on• Edited

Another way:

const reverse = (arr) => {  let left = 0  let right = arr.length - 1  while (left < right) {    [arr[left], arr[right]] = [arr[right], arr[left]]    left++    right--  }  return arr}
Enter fullscreen modeExit fullscreen mode

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromab

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp