Diese Präsentation wurde erfolgreich gemeldet.

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
×

1 von 62 Anzeige

# funwithalgorithms.pptx

Algorithms and data structures in a nutshell

Algorithms and data structures in a nutshell

Anzeige
Anzeige

## Weitere Verwandte Inhalte

Anzeige

### funwithalgorithms.pptx

1. 1. TESS FERRANDEZ
2. 2. extract cells with a given color range schedule jobs on azure batch in the greenest and cheapest way find the direction of moving objects remove the background from a video
3. 3. I’m thinking of a number 1-100 1-100 Hmm… 50? HIGHER 51-100 .. 75? 76-100 .. 88? 76-87 .. 81? 82-87 .. 84? 85-87 .. 86? 85-85 .. 85!!! higher lower higher higher lower
4. 4. BINARY SEARCH
5. 5. 1, 2, 3, 4, 5, 6, 7, 8, 9, ...,85 O(n)
6. 6. 50, 75, 88, 81, 84, 86, 85 log2(100) = 6.64 2^6 = 64 2^7 = 128 O(log n)
7. 7. log2(100) = 7 log2(1 000 000) = 20 log2(1 000 000 000) = 29 1, 2, 3, 4, 5, ..., 1 000 000
8. 8. Find 7 – in a sorted list 0 1 2 3 4 5 6 7 8 [ 1 3 7 8 10 11 15 16 17 ]
9. 9. 8:00 3 6 7 11 2 bph 2 + 3 + 4 + 6 = 15h 3 BPH 1 + 2 + 3 + 4 = 10h 4 BPH 1 + 2 + 2 + 3 1 bph 3 + 6 + 7 + 11 = 27h
10. 10. 10 000 piles and 1 000 000 000 bananas in each!!!
11. 11. 8:00 3 6 7 11 2 bph 2 + 3 + 4 + 6 = 15h … 11 BPH 1 + 1 + 1 + 1 1 bph 3 + 6 + 7 + 11 = 27h P * M calculations 10 000 piles * 1 000 000 000 hours = 10 000 000 000 000 calculations M = Max Bananas per pile P = Piles
12. 12. Koko eating bananas def get_lowest_speed(piles, hours): low = 1 high = max(piles) while low < high: mid = low + (high - low) // 2 if sum([ceil(pile / speed) for pile in piles]) <= hours: high = mid else: low = mid + 1 return low O(p * log max(p)) 10 000 * 29 vs 10 000 * 1 000 000 000
13. 13. BIG O NOTATION
14. 14. print(“fruit salad”) fruits = [“apple”, “banana”, …, “orange”] print(“step 1”) … print(“step 2”) for fruit in fruits: print(fruit) for fruit1 in fruits: for fruit2 in fruits: print(fruit1, fruit2) idx = bsearch(fruits, “banana”) fruits.sort() O(1) O(n) O(n^2) O(log n) O(n * log n)
15. 15. Sleep sort def print_number(number): time.sleep(number) print(number, end='') def sleep_sort(numbers): for number in numbers: Thread(target=print_number, args=(number,)).start() O(n)-ish
16. 16. print(“fruit salad”) fruits = [“apple”, “banana”, …, “orange”] print(“step 1”) … print(“step 2”) for fruit in fruits: print(fruit) for fruit1 in fruits: for fruit2 in fruits: print(fruit1, fruit2) idx = bsearch(fruits, “banana”) fruits.sort() if “peach” in fruits: print(“tropical”) O(1) O(n) O(n^2) O(log n) O(n * log n) O(n) O(1)
17. 17. GRAPHS
18. 18. tree binary search tree trie / prefix tree linked list
19. 19. roads = [ [“Oslo”, “Stockholm”], [“Oslo”, “Copenhagen”], [“Stockholm”, “Copenhagen”], [“Stockholm”, “Helsinki”]] OSLO STOCKHOLM Copenhagen Helsinki roads = [ [“Oslo”, “Stockholm”, 70], [“Oslo”, “Copenhagen”, 50], [“Stockholm”, “Copenhagen”, 30], [“Stockholm”, “Helsinki”, 21]]
20. 20. graph = { “Oslo”: (“Stockholm”, “Copenhagen”), “Stockholm”: (“Oslo”, “Copenhagen”, “Helsinki”), “Copenhagen”: (“Oslo”, “Stockholm”) “Helsinki”: (“Stockholm”) } OSLO STOCKHOLM Copenhagen Helsinki graph = { “Oslo”: { “Stockholm” : 70, “Copenhagen” : 50 }, “Stockholm” : { “Oslo”: 70, “Copenhagen”: 30, “Helsinki”: 21 }, “Copenhagen”: { “Oslo” : 50, “Stockholm”: 30,} “Helsinki”: { “Stockholm”: 21 } }
21. 21. Depth First Search (DFS) def dfs(graph, start, goal): if start == goal: return 0 visited = set([start]) stack = [(start, 0)] while stack: current, steps = stack.pop() for neighbor in graph[current]: if neighbor == goal: return steps + 1 if neighbor not in visited: visited.add(neighbor) stack.append((neighbor, steps + 1)) return -1
22. 22. Breadth First search (BFS) 1 2 2 3 3 4 4 4 def bfs(graph, start, goal): if start == goal: return 0 visited = set([start]) queue = deque([(start, 0)]) while queue: current, steps = queue.popleft() for neighbor in graph[current]: if neighbor == goal: return steps + 1 if neighbor not in visited: visited.add(neighbor) queue.append((neighbor, steps + 1)) return -1
23. 23. Jugs
24. 24. Jugs (5, 0) (2, 3) (2, 0) (0, 2) (5, 2) (4, 3)
25. 25. Jugs (5, 0) (2, 3) (2, 0) (0, 2) (5, 2) (4, 3)
26. 26. Breadth First Search (BFS) Shortest/cheapest path BFS + state in visited (i.e. key or no key) Dijkstra A* Bellman-ford (negative)
27. 27. Course Schedule Course Pre-req 1 0 2 0 3 1 3 2
28. 28. Course Schedule – Topo sort Course Pre-req 1 0 2 0 3 1 3 2 3 1 2 0
29. 29. DYNAMIC PROGRAMMING
30. 30. Fibonacci 1, 1, 2, 3, 5, 8, 13 def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)
31. 31. Fibonacci
32. 32. Fibonacci
33. 33. Memoization (Top down) def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) cache = {0: 0, 1: 1} def fib(n): if n not in cache: cache[n] = fib(n-1) + fib(n-2) return cache[n] @cache def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
34. 34. Tabulation (bottom up) def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) def fib(n): fibs = [0, 1] for i in range(2, n + 1): fibs.append(fibs[i-1] + fibs[i-2]) return fibs[n]
35. 35. 2 7 1 3 9 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 O(2 * n) so for n = 100 we have ~ 1.27 * 10 “operations” n 32 House robber
36. 36. Maxloot(0) = Loot[0] + Maxloot(2) or Maxloot(1) Maxloot(1) = Loot[1] + Maxloot(3) or Maxloot(2) Maxloot(2) = Loot[2] + Maxloot(4) or Maxloot(3) Maxloot(3) = Loot[3] + Maxloot(5) or Maxloot(4) Maxloot(4) = Loot[4] + Maxloot(6) or Maxloot(5) 0 1 2 3 4 2 7 1 3 9
37. 37. Maxloot(0) = Loot[0] + Maxloot(2) or Maxloot(1) Maxloot(1) = Loot[1] + Maxloot(3) or Maxloot(2) Maxloot(2) = Loot[2] + Maxloot(4) or Maxloot(3) Maxloot(3) = Loot[3] + Maxloot(5) or Maxloot(4) Maxloot(4) = Loot[4] + Maxloot(6) or Maxloot(5) 0 1 2 3 4 2 7 1 3 9
38. 38. def rob(loot: list[int]) -> int: @cache def max_loot(house_nr): if house_nr > len(loot): return 0 rob_current = loot[house_nr] + max_loot(house_nr + 2) dont_rob_current = max_loot(house_nr + 1) return max(rob_current, dont_rob_current) return max_loot(0) O(n) so for n = 100 we have 100 “operations” Instead of 1.27 * 10^32
39. 39. SLIDING WINDOW
40. 40. Max sum subarray (of size k=4) 0 1 2 3 4 5 6 7 1 12 -5 -6 50 3 12 -1 1 + 12 - 5 - 6 = 2 12 - 5 - 6 + 50 = 51 -5 - 6 + 50 + 3 = 42 -6 + 50 + 3 + 12 = 59 50 + 3 + 12 - 1 = 64 O((n-k)*k)
41. 41. Max sum subarray (of size k) 0 1 2 3 4 5 6 7 1 12 -5 -6 50 3 12 -1 1 + 12 - 5 - 6 = 2 2 - 1 + 50 = 51 51 - 12 + 3 = 42 42 - (-5) + 12 = 59 59 - (-6) + (-1) = 64 O(n)
42. 42. 1 0 1 2 1 1 7 5 0 0 0 2 0 1 0 5 Always happy: 1 + 1 + 1 + 7 = 10 Total Happy = 16 (10 + 6) O(n) Grumpy Bookstore Owner MAX: 0 2 6 3
43. 43. MAX: 1 2 3 4 O(n) Fruits into baskets
44. 44. Container with most water 1 * 8 = 8 8 * 5 = 40 7 * 7 = 49 8 * 0 = 0 O(n) MAX: 8 49
45. 45. THE ALGORITHM OF AN ALGORITH
46. 46. A L G O R I H T M
47. 47. WHAT’S NEXT
48. 48. TESS FERRANDEZ

### Hinweis der Redaktion

• Examples look small and benign – but look at the Gianormous amount of piles and bananas – Koko must be very hungry

Sidenote – I always add an assert solution.eating_speed([3, 6, 7, 11], 8) == 4 for all test cases so I can experiment with solutions
• Examples look small and benign – but look at the Gianormous amount of piles and bananas – Koko must be very hungry

Sidenote – I always add an assert solution.eating_speed([3, 6, 7, 11], 8) == 4 for all test cases so I can experiment with solutions
• 10 trillion calculations
• Set the values and is_valid for koko eating bananas
• - Very rough calculation to compare algorithms
- Considers worst case scenario
- Use it to compare time and storage used for algorithms
• Set the values and is_valid for koko eating bananas
• Facebook – undirected graph (mutual friends)
Twitter – directed graph, everyone follows Beyonce, but Beyonce doesn’t follow you
Cities and Roads – weighted graph – note the cycle between the first 3 cities
Tasks – weighted (nodes), and disjoint sets – could also have a flow ??? Not sure if it fits here
Matrix – neighbors are UDLR (if not blocked) + some are ok only if you have the key
Horse – neighbors are 2+1 away (add animation)
• Special Graphs

Tree – doesn’t need to be binary – animate in mom2
A Tree is a DAG but not all DAGs are trees – animate in link between mom and 2nd grandma
Binary Search Tree – Very fast structure for sorted sets
Trie/Prefixtree (or suffix) – used for pattern matching – ex routes in APIs
Linked list – single next rather than multiple

Also others,
Minimum Spanning Tree (simplified tree with shortest paths)
Segment Tree (for segment queries ex. sum[a-f] – often in databases – heard its also used for shazam searches)

• Great for exploration
Not good for shortest path – we need to find all paths
• Great for full exploration
Great for shortest path
• McClane and Zeus (Bruce Willis and Samuel L Jackson)
• Great for full exploration
Great for shortest path
• Great for full exploration
Great for shortest path
• Great for full exploration
Great for shortest path
• Sets
Groups
Islands
Circle of friends
• Sets
Groups
Islands
Circle of friends
• Great for full exploration
Great for shortest path
• Great for full exploration
Great for shortest path
• The idea of saving for example a visited set – so we don’t revisit nodes we already checked
saves us from infinite loops, but is also a type of “caching” – which brings us to “dynamic programming”
• Just adding the little @cache in here might save a few roundtrips to the database or what not
• A special case of dynamic programming
• A special case of dynamic programming
Uppercase/lowercase?
Negative numbers?
Sorted?
What do I actually need to calculate?
Memory/Time limits?
Have I seen similar questions before?

Don’t simulate the process or find all paths if you only need to find out the number of steps
Maybe we can just find a mathematical pattern

LIMIT:
A time of log n => binary search or divide and conquer
Very large sets mean we need to think more about time/space

GROK:
Draw the algorithm
Go through all the examples manually
Find patterns
Draw diagrams and arrows and whatever else you need

OMG!
Is “abba” an anagram of “baba”? => Sorted(“abba”) = SORTED(“BABA”)
Or same character counts
A recipe could be represented As a graph of tasks
MaxLoot[i] = max(Loot[i] + maxloot[I + 2], MaxLOOT[I + 1])
Is power of 2? => binary representation has one 1
Is palindrome => has only one char with odd count

REDUCE:
Find high/low limits
Design is-valid
Implement binary search

IMPLEMENT:
Consider data structures
Use templates / algos from internet
Start simple (maybe brute force) and optimize

ITS ONLY NOW THAT WE START IMPLEMENTING

Write lots of pseudo code
Optimize one piece at a time

TEST:

BE HAPPY:

MORE VARIATIONS:
Try variations
Limit yourself
Look at other peoples solutions
• A special case of dynamic programming