Arrays and Hashing Array basics

51. Reverse an Array

Easy

You are given an array of integers nums. Reverse the order of its elements and return the array. The first element becomes the last, the second becomes the second to last, and so on.

Do it in place: change nums itself and use only O(1) extra memory. Only positions change. Every value stays the same, and the array keeps its length.

Example 1

Input: nums = [4, 9, -2, 7, 1]

Output: [1,7,-2,9,4]

Explanation: The first and last elements trade places, then the second and fourth. The middle element, −2, stays where it is.

Example 2

Input: nums = [3, 8, 8, 5, 0, 6]

Output: [6,0,5,8,8,3]

Explanation: With six elements there is no middle element, and all three pairs trade places. The two 8s swap with each other, so they look unchanged.

Example 3

Input: nums = [-1000000000]

Output: [-1000000000]

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 2, 3, 4]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.