



























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




























Abstract Data Type - ANS-can be implemented in many different ways. -Stacks and Q's are abstract data types that can be implemented in many ways. Q's often implemented as Linked List. Applications of DFS - ANS1) Detecting a cycle - if we see a back edge during DFS we have a cycle
AVL Tree - ANSa self-balancing Binary Search Tree where difference between height of left and right subtrees cannot be more than one for all nodes (doesn't need to be complete. A complete has its nodes all the way to the left and while an AVL tree keeps the left and right subtree depth the same, it doesn't order the nodes all the way to the left) worst case complexity (search, insert, delete) - lgn Binary Heap and Complexity (search, insert, delete, extractMax/extractMin, peek) - ANSheap w/ at most two children. Often stored in an array. -must be complete (all levels except last are full, and all nodes all the way to the left). New values added @ bottom level left to right. -being complete guarantees the correct shape and worst case O(lgn) Search: Avg - N, Worst - N ( Insert: Avg - 1, Worst - lgn Delete: Avg- lgn, Worst - lgn Peek: O(1)
2^(# iterations) = (array size) -Binary Search is O(log n) Binary Search Time Complexity alternate way of thinking - ANS-each time we split the array in half we have: n/2, n/4, n/8 etc... items left. When we split enough we get n/2^i = 1 (where i is the number of comparisons) 1 = n/2^i 2^i = n i * log(2) = log n Binary Search Tree (BST) - ANSevery value on the left is smaller, every value on right is larger Binary Tree - ANS-has at most two children (0,1, or 2 children) Binary Tree - Level vs number of nodes - ANSeach new level can have twice as many nodes as the one before it. We're adding a power of two at each level, Binary Tree - Search(item), Delete(item), Insert Complexity - ANSSearch - O(n) (any traversal algo is linear since BT there's no order to nodes) Delete - O(n) (starts with search since we need to find what we want to delete. Deltions are tricky, sometimes need to promote grandchildren up and/or re-arrange nodes)
Insert - avg=> lgn, worst=> n BST - Search, Insert, Delete Complexity - ANSSearch, Insert, Delete: avg=> lgn worst case => n -worst case when we degenerate to linked list Collection Data Structure Comparisons - ANSLists - indexed elements. good for accessing elements in the middle. insertion and deletion messy O(n). Has potentially unused memory space Linked List - better for insert/delete O(1), but difficult to access elements in the middle Stack - easy to implement with a LL, easy push and pop O(1) Queue - easy to implement, fast enqueue/dequeue Collections - ANSa group of things with no order -(we can't say give me the 3rd element in the collection) -can have different types -many data structres are extensions of collections: lists, arrays, LL, stacks queues
Complexity - sort each string in a list, then sort the list itself - ANS['aba', 'cbd', 'cdc'] ===> ['aab', 'bcd', 'ccd'] -a = # elements in list -s = longest string
Degree - The number of edges that are connected to vertex (loop edges count as 2)
self.dfsRecursive(neighbor) Efficiency/Complexity - ANShow well your using your computer's resources to get a particular job done. Thought about it in terms of space and time -there are tradeoffs for algorithm efficiency - slow methodical approach vs faster method that reduces repetition -use heuristics that are not as precise but still pretty good -efficiency can rely on creativity, but there are often tips and tricks Efficient Hash Function - ANS-choose between
-no root node -nodes generally store data, but edges can also store data in the form of weights Graph - Disconnected vs Connected - ANSDisconnected - has vertex/node that can't be reached by other vertices (undirected) Connected - has no disconnected vertices Graph - Weakly Connected vs Strongly Connected vs Complete - ANS-weakly and strongly generally apply to directed graphs Weakly connected - if considering as an undirected graph, it is connected (there may not be a path b/w some pairs of vertices) Strongly Connected - for a directed graph, there is a path between all pairs of vertices. Unilaterally connected - semi-path (touches all vertices). There's a path from A to B, but not necessarily B to A Complete - an undirected graph - there is a path between every pair of nodes Graph Connectivity - ANS-measures minimum # of elements that need to be removed for a graph to become disconnected
add vertex => 1 remove vertex => V Add/remove edge => 1 query => 1 space => V+E Graph Representation comparison - when to use Adj Matrix vs Adj List - ANS- adjacency matrix best for dense -adjacency list best for sparse Adj List is overall more efficient Graph Search vs Graph Traversal - ANSGraph search - stop searching when you find the element you're looking for Graph traversal - look at every element Hash Table - ANS-a data structure that implements an associative array abstract data type, a structure that can map keys to values -allows you to do lookups in constant time -take some value ==> convert value based on formula ==> spits out coded version of value ==> index into hash table
-common pattern is to take modulo/remainder of last few digits of big number Hash Table - Linear Probing vs Chaining - ANSChaining
Pros: simpler to implement, very flexible size, less sensitive to hash function or load factors. Cons: wastes space in that some parts of hash table are never used. Open Addressing:
Pros: Better cache performance as everything in same table Cons: more computation, table may become full, suffers from clustering Hash Table Collision - ANS-two different inputs generate the same hash value/index -fixed via chaining, open addressing, or double hashing Hash Table Load Factor - ANS-gives a sense of how full a hash table is. It's also the expected length of a chain (if we're using chaining) load factor less than 1 => mostly empty spaces, wasting space
HashTable Collisions - Open Addressing / Probing (closed hashing) - ANS- when a collision occurs, we look for the next open space (in linear) (also quadratic, double hasing etc..) -CPython uses random probing, where the next slot is picked in a pseudo random order HashTable Collisions - Separate Chaining (open hashing) - ANS-each cell of table points to a linked list -Pros: simple to implement, the table never fills up and we're always able to add more elements to chain -Cons: wastes space in extra linked list, slower lookup (O(n) worst case if all elements in one linked list Heap - ANSspecific type of tree where root element is either max or min value max-heap => all parents >= children min-heap => all parents <= children -generic heap can have any number of children. Binary heap can have at most two children -often stored in an array (less space storage vs using Nodes with a bunch of left/right pointers) Heap vs Binary Heap - ANS-Heap is any number of children, binary heap is 2
-binary heap is a complete tree - all levels except last filled - won't degenerate Linked List Time Complexity - ANSinsert/delete - O(1) *(removing last element w/ no tail can be O(n) get item - O(n) Linked Lists - ANS-an extension of a list, but no indices. Each element can have a next and previous pointer -much easier to insert/delete since we're just moving pointers -difficult to access elements in the middle -worse locality of reference than arrays Lists/Arrays - ANSall the properties of a collections but it's ordered -In python, lists are implemented as Arrays.
insert(item, priority): Inserts an item with given priority. getHighestPriority(): Returns the highest priority item. deleteHighestPriority(): Removes the highest priority item. -used in algos like Djikstra's shortest path, and Prim's min spanning tree Priority Queue implementation array vs heap - ANSSimple Array:
get/deleteHighestPriority O(1) (get first element) insert() O(n) (append) Linked List
get/deleteHighestPriority - N (slightly better on delete) insert() - 1
insert() - lgn getHighestPriority() - 1 deleteHighestPriority() - lgn Python List Time Complexity - ANSappend - O(1) (amortized) pop - O(1) insert and remove - O(n) get item - O(1) in membership testing - O(n) -largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move). -insertion and deletion messy (due to fixed sizes -good for accessing elements in the middle -If you need to add/remove at both ends, consider using a collections.deque instead. Python heapq operations complexity (push, pop, - ANSpush - lgn pop - lgn build heap - nlgn (push all items onto heap - nlgn)