Given an array of integers arr
, return whether the array is sorted in ascending order.
To solve this problem, you have to check whether the values are in increasing order.
To do this, you can check that each element is greater or equal to the previous element, like this:
To write this in code, you can simply loop over the entire array, like this:
This code is mostly correct, but there's a minor issue. When i=0
, you run into the case where the previous element doesn't exist, like this:
We shouldn't run this case, because our code will break. You can omit this case from the loop, by making the range start at 1, by writing range(1, len(arr))
. Here's the solution to the problem:
Time Complexity O(n). This algorithm takes O(n) time, because we have to loop over the entire array. The letter "n" refers to the size of the input - in this problem "n" is the length of the array.
Space Complexity O(1). We don't have to store any variables in memory, so the space is just O(1).
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()