Skip to content

Instantly share code, notes, and snippets.

View wilderfield's full-sized avatar

Bryan Lozano wilderfield

View GitHub Profile
def dfsRecursive(node,visited=set()):
visited.add(node)
# Process this node here
for neighbor in getNeighbors(node):
if neighbor not in visited:
dfsRecursive(neighbor,visited)
return
@wilderfield
wilderfield / dfsIterative.py
Last active June 5, 2020 08:25
DFS Iterative
def dfsIterative(node,visited=set()):
stack = [node]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
# Process this node here
for neighbor in reversed(getNeighbors(node)): # Reversal not mandatory
@wilderfield
wilderfield / graph.py
Created June 6, 2020 01:56
Adjacency List
graph = [[1,3,5], # node 0 connects out to node 1,3,5
[2,4], # node 1 connects out to node 2,4
[4], # node 2 connects out to node 4
[1], # node 3 connects out to node 1
[5], # node 4 connects out to node 5
[]] # node 5 connects out to nothing
# This function returns the neighbors of a given node in a list
def getNeighbors(node):
return graph[node]
@wilderfield
wilderfield / bfsIterative.py
Last active June 6, 2020 06:55
BFS Iterative
def bfsIterative(node,visited=set()):
queue = [node]
while queue:
node = queue.pop(0) # Pop first node in list
if node not in visited:
visited.add(node)
# Process this node here
for neighbor in getNeighbors(node):
@wilderfield
wilderfield / datastructures.cpp
Created July 14, 2020 01:25
All Cpp STL Data Structures in One Go!
#include <iostream> // cout
#include <vector> // Dynamic Array
#include <list> // Doubly Linked List
#include <deque> // Double Ended Queue (Circular Buffer)
#include <queue> // FIFO Queue, and Max Heap (Priority Queue)
#include <stack> // LIFO Stack
#include <set> // Ordered Set (BST - Red/Black)
#include <map> // Ordered Map (BST - Red/Black)
@wilderfield
wilderfield / binarySearch.py
Last active May 8, 2021 18:00
Python Binary Search
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l = 0
r = len(nums)-1
while l <= r:
m = l+(r-l)/2
@wilderfield
wilderfield / graphHasCycle.py
Last active May 8, 2021 18:48
Detect a Cycle in a Directed Graph Using DFS
# Constants
UNVISITED = 0
VISITED = 1
EXPLORED = 2
# Test Adjacency List Graph
# 0 -> 1 -> 2 -> 3
graph = [[1],
[2],
[3],
@wilderfield
wilderfield / topSort.py
Created May 9, 2021 03:16
Topological Sort
# Constants
UNVISITED = 0
VISITED = 1
EXPLORED = 2
# Test Adjacency List Graph
# 0 -> 1 -> 2 -> 3
graph = [[1],
[2],
[3],
# This approach does not sort nums in place
def merge(numsLeft, numsRight):
result = []
i = 0
j = 0
while i < len(numsLeft) and j < len(numsRight):
if numsLeft[i] <= numsRight[j]:
result.append(numsLeft[i])
@wilderfield
wilderfield / quickSort.py
Last active June 1, 2021 07:03
Quick Sort
from random import randint
def partition(nums, l, r, pIdx):
pVal = nums[pIdx]
# Swap pivot index with the right most
nums[r], nums[pIdx] = nums[pIdx], nums[r]
# Everything to the left of index i