Tricky Time Complexity

list

List is like array so operation at beginning of the list is costly.

  • append: O(1)O(1)
  • insert(0, item): O(n)O(n)
  • pop: O(1)O(1)
  • pop(0): O(n)O(n)

deque

Because deque at its core is a double-linked list so it's more efficient than list

  • appendleft: O(1)O(1)
  • append: O(1)O(1)
  • pop: O(1)O(1)
  • popleft: O(1)O(1)
  • in: O(n)O(n) — since it's a linked list

Heap Theory

  • findMin(): O(1)O(1)
    • In python we just query heap[0]
  • pop(): O(logn)O(logn)
    • When calling pop() we need to start building the heap again to determine the lowest
  • insert(): O(logn)O(logn)

set

  • in: O(1)O(1)
  • x.union(y): O(x+y)O(x + y)
  • x.intersect(y): O(min(x,y))O(min(x, y))

Sorted Set

  • in: O(logn)O(logn)
  • add: O(logn)O(logn)
  • remove: O(logn)O(logn)

BFS

  • O(V+E)O(V + E) with
    • VV number of vertices — which is the same as the number of nodes.
      • So given an m×nm \times n array, VV would be m×nm \times n
    • EE number of edges — which is the connection between a node
      • For example a 3x2 array would have 7 EE.
      • We can use the following formula: E=m×(n1)+n×(m1)E = m \times (n-1) + n \times (m-1)
        • Which in this case E=3×1+2×2=7E = 3 \times 1 + 2 \times 2 = 7

DFS recursion

  • Depends on how we call the recursion in the for dr,dc loop.
    • If there is 4 and the total node we travel is m x n then it would be O(4(m×n))O(4^{(m \times n)})
    • If there is 2 direction and the total node we travel is m + n then it would be O(2(m+n))O(2^{(m + n)})

Trie

  • Add w words of size l: O(wl)O(w * l)
  • Search for word of size l: O(l)O(l)
  • Prefix O(prefix)O(prefix)

Skip List

  • Search: O(logn)O(logn)
  • Insert: O(logn)O(logn)
  • Delete: O(logn)O(logn)

Permutation

  • Time compexity: O(n×n!)O(n \times n!) since the tree expands out from n items at the root and then n-1, n-2, n-3,... and at each pivot (start index) we have n!n! ways of choosing

Combination Sum

  • Time complexity: O(2target)O(2^{target}) since at each number we can either take or not (2 choices), and then we can choose duplication so sum up to a target

Subset

  • Time complexity: O(n×2n)O(n \times 2^{n}) for nn number we will have 2n2^n subsets. And we perform the basket.copy() which will be O(n)O(n)