Reverse a 1-D NumPy array with slicing

Quick Overview

Reverse a 1-D NumPy array using a stepped slice, without np.flip or a Python loop. It tests how negative-step slicing works, whether the result is a view or a copy, and what a negative stride means for code that later modifies or shares the array.

Reverse a 1-D NumPy array with slicing

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Given a 1-D `np.ndarray`, return a new array with the elements in reverse order. Reverse it with a stepped slice (`arr[::-1]`). Do not use `np.flip`, `np.flipud`, or any Python loop. For example: ```python arr = np.array([1, 2, 3, 4, 5]) reverse(arr) # array([5, 4, 3, 2, 1]) ``` ```hint New or shared The task asks for a new array. Check whether the slice you produce owns its data or reads the input's buffer. ``` ### What a Strong Answer Covers - Explains how a step of -1 walks the array from the last element to the first - Says whether the slice is a view or a copy and what its stride looks like - Decides whether the result must be independent of the input and copies when it must - States the time and memory cost of the slice and of the copy ### Follow-up Questions - Does `arr[::-1]` copy or view the data? - How would you reverse a 2-D array along its rows, its columns, or both? - Is `arr[:] = arr[::-1]` a safe way to reverse an array in place?

Overview: Reverse a 1-D NumPy array using a stepped slice, without np.flip or a Python loop. It tests how negative-step slicing works, whether the result is a view or a copy, and what a negative stride means for code that later modifies or shares the array.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

Given a 1-D np.ndarray, return a new array with the elements in reverse order.

Reverse it with a stepped slice (arr[::-1]). Do not use np.flip, np.flipud, or any Python loop.

For example:

arr = np.array([1, 2, 3, 4, 5])
reverse(arr)  # array([5, 4, 3, 2, 1])

What a Strong Answer Covers Guidance

  • Explains how a step of -1 walks the array from the last element to the first
  • Says whether the slice is a view or a copy and what its stride looks like
  • Decides whether the result must be independent of the input and copies when it must
  • States the time and memory cost of the slice and of the copy

Follow-up Questions Guidance

  • Does arr[::-1] copy or view the data?
  • How would you reverse a 2-D array along its rows, its columns, or both?
  • Is arr[:] = arr[::-1] a safe way to reverse an array in place?