Templates Flashcards

1
Q

What is the binary search template?

A
boolean binarySearchIterative(int[] nums, int num) {

    if (nums.length == 0) {
      return false;
    }

    int low = 0;
    int high = nums.length - 1;

    while (low <= high) {
      int mid = (low + high) >>> 1; // no overflow

      if (num == nums[mid]) {
        return true;
      }

      if (num < nums[mid]) {
        high = mid - 1;
      } else {
        low = mid + 1;
      }
    }
    return false;
  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the in-order-traversal template?

A
void inOrderTraversal(Node<Integer> node) {
        if (node == null) {
            return;
        }
            inOrderTraversal(node.left);
            System.out.println(node.val);
            inOrderTraversal(node.right);
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the pre-order-traversal template?

A
void preOrderTraversal(TreeNode node) {
        if (node == null) {
            return;
        }
        System.out.println(node);
        preOrderTraversal(node.left);
        preOrderTraversal(node.right);
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the post-order-traversal template?

A
void postOrderTraversal(Node<Integer> root) {
        if (root != null) {
            postOrderTraversal(root.left);
            postOrderTraversal(root.right);
            System.out.println(root.val);
        }
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the DFS on tree template?

A
Node dfsTree(Node node, int target) {
    if (node == null)
      return null;
    if (node.getElement() == target) 
      return node;

    Node left = dfsTree(node.getLeft(), target);

    if (left != null)
      return left;

    Node right = dfsTree(node.getRight(), target);

    return right;
  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the sliding window template?

A
function fn(arr):
    left = 0
    for (int right = 0; right < arr.length; right++):
        Do some logic to "add" element at arr[right] to window

        while WINDOW_IS_INVALID:
            Do some logic to "remove" element at arr[left] from window
            left++

        Do some logic to update the answer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly