Leetcode - Data Structure
Tree
Insights
- When search on level order, bfs is better than dfs
Graph
Define a graph
use self-defined class GNode to define the node, use defaultdict to save all edges
class GNode(object):
def __init__(self):
self.inDegree = 0
self.outNode = []
Class Solution(object):
def findOrder(self, numCourses, prerequisites):
from collections import defaultdict, deque
graph = defaultdict(GNode)
Topological Sort
Main idea
sort in the number of in-degree
Algorithm
- use dictionary to store the information on all edges: {key: inNode, value: {inDegree, outNode}}
- use deque to store the node with inDegree == 0
- Use bfs to explore all nodes in the order of number of inDegree. For each node N in deque, we delete all edges connected with N and minus the inDegree of the nodes from N. If there is new node becomes inDegree == 0, add it into deque.
Time Complexity
O(V+E)
Leetcode example: 210. Course Schedule II
More in details
class GNode(object):
def __init__(self):
self.inDegree = 0
self.outNode = []
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
from collections import defaultdict, deque
graph = defaultdict(GNode)
courseOrder = []
for prerequisite in prerequisites:
nextCourse, prevCourse = prerequisite[0], prerequisite[1]
graph[prevCourse].outNode.append(nextCourse)
graph[nextCourse].inDegree += 1
totalEdges = len(prerequisites)
nodepCourses = deque()
for course in range(numCourses):
if graph[course].inDegree == 0:
nodepCourses.append(course)
removedEdges = 0
while nodepCourses:
course = nodepCourses.popleft()
courseOrder.append(course)
for node in graph[course].outNode:
graph[node].inDegree -= 1
removedEdges += 1
if graph[node].inDegree == 0:
nodepCourses.append(node)
if totalEdges == removedEdges:
return courseOrder
return []
Shortest Path
Minimum Generate Tree
Hash Table
LinkedList
Tricks
We can add an additional node before the head or after the tail to simplify the processing.
DoubleLinkedList
Heap (Priority-queue)
Functions
- heappush(heap, [key, value])
- key, value = heappop(heap)
heap = []
for value, num in valueMap.items():
heappush(heap, [-num, value])
while heap:
key, value = heappop(heap)
Tricks
The default order for heap is increasing. If we want to construct a decreasing heap, we can use -key.
Leetcode Examples
347. Top K Frequent Elements
Main idea
Heap sort
from collections import defaultdict
valueMap = defaultdict(int)
for num in nums:
valueMap[num] += 1
heap = []
for value, num in valueMap.items():
heappush(heap, [-num, value])
i = 0
answer = []
while i < k:
num, value = heappop(heap)
answer.append(value)
i += 1
return answer