Reverse a Sequence of Node Values
Linked ListsAuto-graded · 22 test casesLast updated
Tests the ability to reverse a sequential list of numbers efficiently, mimicking linked list reversal operations.
Given a list of integers values representing the sequential elements of a data structure (such as node values in a singly linked list), return a new list containing all elements in reverse order.
An empty input list should return an empty list.
Constraints:
0 <= len(values) <= 10^4-10^9 <= values[i] <= 10^9
Examples
Example 1
Input: reverse_list([1, 2, 3, 4, 5])
Output: [5, 4, 3, 2, 1]
Example 2
Input: reverse_list([])
Output: []
Hints
Hint 1
Think about reversing the order of elements either sequentially or using modern array manipulation techniques.
Hint 2
Make sure to handle edge cases like an empty input list or single-element inputs.
Hint 3
For a standard Python list, a single slicing operation can reverse all elements efficiently.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To reverse a list of elements, we can iterate through the list from end to beginning or construct a new list containing the elements in inverted order. In Python, sequence slicing with a negative step size (values[::-1]) provides a direct, highly optimized mechanism for achieving this.
If implemented using pointers as in explicit linked list manipulation:
- Maintain a pointer to track the processed reversed portion.
- Iterate through each element, linking it behind the previous node.
- Return the head of the new sequence.
Since the input here is a standard list representing the node sequence, slicing or standard list reversal produces the correct inverted output.
Complexity
- Time Complexity: $\mathcal{O}(n)$, where $n$ is the number of elements in
values. Each element is visited once. - Space Complexity: $\mathcal{O}(n)$ auxiliary space to store and return the newly created reversed list.
Python Solution
from typing import List
def reverse_list(values: List[int]) -> List[int]:
return values[::-1]