Given a sorted array arr
and an integer high
, return the largest element in the array with a value less than high
.
1. Recursion
To solve this problem, you should use a Binary Search since the array is sorted. To do a binary search, you should look at the middle value in the array, and either search to the left of it, or search to the right of it.
If the middle value is less than high
, you want to find a larger value. This means you should continue searching towards the right.
If the middle value is less than high
, you want to find a smaller value. This means you should continue searching towards the left.
Here's the recursion, combining these two cases:
The recursion always moves towards the high
value. This means the solution to the problem is the most recent value that we see that's less than high
. Here's how you keep track of this:
2. Base case
The easiest way to code up a stopping point for a binary search is when the search is empty, or when j is to the left of i.
3. Code
Here's the recursive code:
Time Complexity O(logn)
Space Complexity O(logn) for the Call Stack.
We can easily convert this to iterative code to get rid of the Call Stack:
Time Complexity O(logn)
Space Complexity 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()