Exercises
We will resolve a few array exercises from Hackerrank using the concepts we learned in this chapter.
Reversing an array
The first exercise we will resolve the is reverse array problem available at https://www.hackerrank.com/challenges/arrays-ds/problem.
When resolving the problem using JavaScript or TypeScript, we will need to add our logic inside the function reverseArray(a: number[]): number[] {}
, which receives an array of numbers and it is also expecting an array of numbers to be returned.
The sample input that is given is [1,4,3,2]
and the expected output is [2,3,4,1]
.
The logic we need to implement is to reverse the array, meaning the first element will become the last and so on.
The most straightforward solution is using the existing reverse
method:
function reverseArray(a: number[]): number[] {
return a.reverse();
}
This is a solution that passes all the tests and resolves the problem. However, if this exercise is being used in technical interviews, the interviews...