Reverse Like Linked List
Given an array representing a linked list, reverse the order of its elements and return the reversed array. This is equivalent to reversing a singly linked list, where each node's next pointer is redirected to point to the previous node.
For example, reversing [1, 2, 3] produces [3, 2, 1]. Reversing [5] produces [5] (a single element reversed is itself). Reversing an empty array produces []. Reversing [1, 2, 3, 4] produces [4, 3, 2, 1].
Reversing a linked list is one of the most classic linked list problems and is frequently asked in technical interviews. The array version is simpler because you can use built-in reversal methods, but the underlying concept — reversing the direction of pointers — is the same.
In a real linked list, reversal requires three pointers (previous, current, next) to iteratively redirect each node's next pointer. In array form, you can use a two-pointer swap approach: swap elements at opposite ends, moving inward until the middle is reached.
Edge cases include empty arrays (return []), single-element arrays (return the same array), and two-element arrays (simple swap). The solution works the same regardless of the values or length.
Example Input & Output
Reverse order
Algorithm Flow
Solution Approach
Reverse the array using the built-in reverse method or a two-pointer swap.
The simplest approach uses slice() to create a copy (avoiding mutation of the input) and then reverse() to reverse it. Alternatively, you can implement the reversal manually using two pointers: initialize i = 0 and j = arr.length - 1, swap arr[i] and arr[j], then increment i and decrement j until i >= j.
Time complexity is O(n), space complexity is O(n) for the copy or O(1) for in-place reversal.
Best Answers
class Solution {
public int[] solution(int[] nums) {
int[] r=nums.clone();
for(int i=0,j=r.length-1;i<j;i++,j--){int t=r[i];r[i]=r[j];r[j]=t;}
return r;
}
}Related Linked List Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
