DS&A Flashcards
Improve retention and memory of basic data structures and algo concepts (2 cards)
1
Q
Binary Search
How to implement canonical BS?
A
def search(nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l <= r: m = (l+r)//2 if target < nums[m]: r = m - 1 elif target == nums[m]: return m else: l = m + 1 return -1
- Helps to search sorted array
- O(log(n)) TC, O(1) SC
- We need the
l<=r
to handle the caselen(nums)==1
- If we have
l<=r
andr=m
orl=m
then no convergence (time out)
2
Q
DFS
How to implement DFS in a tree? What is it used for?
A
- DFS can be implemented recursively, then it’s easy to traverse a tree pre-order, in-order or post order
- To reduce the call stack we can implement DFS iteratively using a stack structure; pre-order DFS
def dfs_pre(root: TreeNode): logger.info("DFS pre-order") stack = deque() stack.append(root) while stack: node = stack.pop() logger.info("At node %d", node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left)