Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

ab
ab

Posted on

     

How Would You Reverse an Array In Place?

Let's say you were given an array of characters, such as['a', 'b', 'c', 'd', 'e']. How would you reverse this array in place (that is, have a space complexity of O(1))?

One solution to this problem involves having two pointers, which start at both ends of the array. Then, swap the elements at those points in the array. Once both elements have been swapped, move both pointers toward the middle, and keep doing this until the left pointer is no longer smaller than the right pointer.

To start, set two variables for the two pointers--

functionreverseArray(arr){letleftPointer=0letrightPointer=arr.length-1//...}
Enter fullscreen modeExit fullscreen mode

Then, initiate a while loop to keep going as long asleftPointer is less thanrightPointer. When I initiate while loops, I like to immediately include an increment or decrement--this helps me avoid accidentally creating an infinite loop.

functionreverseArray(arr){letleftPointer=0letrightPointer=arr.length-1while(leftPointer<rightPointer){//...leftPointer++rightPointer--}}
Enter fullscreen modeExit fullscreen mode

This is the tricky part of the problem: swapping the elements. One solution to this involves temporarily storing one of the elements in a variable. Then, set one element to the other, and set the other to the temporary.

functionreverseArray(arr){letleftPointer=0letrightPointer=arr.length-1while(leftPointer<rightPointer){lettemporary=arr[leftPointer]arr[leftPointer]=arr[rightPointer]arr[rightPointer]=temporaryleftPointer++rightPointer--}}
Enter fullscreen modeExit fullscreen mode

And that's it! If you tested this out with the array['a', 'b', 'c', 'd', 'e'], the function would return['e', 'd', 'c', 'b', 'a']. The time complexity for this solution would be linear, O(n).

Top comments(1)

Subscribe
pic
Create template

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

Dismiss
CollapseExpand
 
ionellupu profile image
Ionel Cristian Lupu
Author of Typetron. Passionate about web development. Typescript enthusiast.
  • Joined

This can be done with only theleftPointer. TherightPointer can be deduced fromarr.length - leftPointer - 1.

Also, isn'tArray.prototype.reverse() O(n)? It looks like, asper spec, they do almost the same thing:

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