Given an array arr
, reverse the array.
You should solve this problem in-place, without creating a new Array.
You need to solve this problem in-place, without creating a new Array. The idea for reversing the array is to swap all the elements in pairs, like this:
When you you're done, you'll end up with the reversed array, like this:
To do this, you can use 2 pointers, one starting at the right side of the array n-1
, and one starting at the left side 0
.
You keep moving the pointers inwards and swapping elements, until each element has been swapped with the element on the opposite side. You stop when the pointers cross each other. Here's the code for this:
Time Complexity O(n). We loop through the entire array.
Space Complexity O(1). We don't have to store any variables. The size of the input never counts towards the space complexity, which is why the space complexity is O(1) and not O(n).
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()