Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inplace array reversal #336

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
- [H-Index](src/array/h-index.js)
- [H-Index II](src/array/h-index-ii.js)
- [Pour Water](src/array/pour_water.js)
- [Inplace Array Reversal](src/array/inplace-reverse-array.js)

### Matrix

Expand Down
50 changes: 50 additions & 0 deletions src/array/inplace-reverse-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Reverse Inplace Array
*
* Given an Array arr.
*
* We want to reverse order of elements inside .
* We will also take edge cases into account
* For eg:- In case parameter passed is null or undefined we may want to throw error
* In case parameter passed is not an array
* In case parameter passed has length 0
*
* For example, given
*
* arr = [1,2,3,4,5,6,7,8,9]
* We should return
* [9,8,7,6,5,4,3,2,1]
*
*/

/**
* @param {number[]} arr
* @return {number[]} arr
*/
function inPlaceArrayReverse(arr) {
// edge cases
if(!arr){
throw new Error('undefined input');
}

if(!Array.isArray(arr)){
throw new Error('not an array')
}

if(arr.length === 0){
throw new Error('array empty')
}

var len = arr.length - 1;
for(let j=0; j<len/2; j++ ){
let temp = arr[j];
arr[j] = arr[len-j];
arr[len-j] = temp;
}

return arr;
}

let testArray = [1,2,3,4,5,6];

console.log('Printing the inplace reverse of a given array: ', inPlaceArrayReverse(testArray));