# the best aproach is to create some kind of constant value for each
# diagonal, you can then use sets to check if something is already there
# for top left to bottom right, row - col
# for bottom left to top right, row + col
_set = set()
neg_diagonal = row - col
if neg_diagonal in _set:
# that is already in set
else:
# not already in set
Check groups, aka 3x3 sudoku
# div integers, note ints div to floor
grid = # a 2d array containing the sudoku
square = defaultdict(set) # each square is defined by row / 3 and col / 3
for row in range(9):
for col in range(9):
if grid[row][col] in square[(row // 3, col // 3)]:
# num already in grid
else:
square[(row // 3, col // 3)].add(grid[row][col])
Pair aka tuple
pair = (x, y)
pairs_arr = ((x, y) for x, y in zip(og_x, og_y))
pair.sort() # will sort by x
Set
_set = {"apple", "banana", "cherry", False, True, 0}
_set = set() # empty set
if i in _set:
...
_set.add(1)
_set.remove(1)
Defaultdict
_dict = defaultdict(lambda: False)
# or collections.defaultdict
_dict_with_set = collections.defaultdict(set)
if i in _dict and _dict[i]: # check if item in dict
...
Heap (key-value)
Queue (FIFO)
Stack (LIFO)
stack = []
x = stack.pop()
stack.append(x)
Linked List
fast and slow pointers
find half way
# in even list, to select right choose head, for left choose head.next
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
find loop
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True # loop exists
return False # loop not exists
return head of loop
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if not fast or not fast.next:
return None # return if no loop
slow2 = head
while slow != slow2:
slow = slow.next
slow2 = slow2.next
return slow
stack = [start]
visited = set()
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
if node == target:
return True # Target found
for neighbor in graph[node]:
if neighbor not in visited:
stack.append(neighbor)
return False
BFS
queue = deque([start])
visited = set()
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
if node == target:
return True
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
return False
Backtracking
def backtracking(val):
if # met some condition):
return True
result = False
for i in range(n): # or look at nayboars
# do some checks
result = backtracking(val) or result
return result
Bubble sort
for i from 1 to N
for j from 0 to N-1
if a[j] > a[j + 1]
swap(a[j], a[j + 1])
Insertion sort
for i from 1 to length(arr) - 1
j = 1
while j > 0 and arr[j-1] > arr[j]
swap(arr[j-1], arr[j])
j = j - 1