eagle0504 commited on
Commit
8b346de
·
verified ·
1 Parent(s): 33dc5e1

Create sections/01_software_engineer_basics.py

Browse files
sections/01_software_engineer_basics.py ADDED
@@ -0,0 +1,1298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def software_engineer_basics():
2
+ import streamlit as st
3
+
4
+ st.write("# Welcome to Software Engineer Basics! 👋")
5
+ st.sidebar.success("Select a session from the menu of content.")
6
+
7
+ st.markdown(
8
+ r"""
9
+ # Software Engineering Interviews
10
+
11
+ Software engineering interviews often test a candidate's ability to solve problems, write code, and communicate their thought process. In this guide, we will discuss several key concepts that frequently come up in these interviews, along with Python examples for each.
12
+
13
+ For more details, I recommend the following [link](https://github.com/yiqiao-yin/Data-Science-Interview-Questions-Answers).
14
+
15
+ ## Big $\mathcal{O}$
16
+
17
+ **Simple Explanation**: Big $\mathcal{O}$ notation is a way to describe how long an algorithm takes to run or how much memory it uses as the size of the input increases. It gives us an upper bound on the runtime.
18
+
19
+ ### Tricks
20
+
21
+ 1. Include all the things
22
+ 2. Use logiscal variable names
23
+ 3. Define the variables you need
24
+ 4. Adding vs. multiplying
25
+ 5. Drop constants
26
+ 6. Use big-O for space; remember the call stack!
27
+ 7. Drop non-dominant terms
28
+
29
+ **Example**:
30
+ Suppose we want to find if a number exists in a list. One way is to look at each number until we find it.
31
+
32
+ ```python
33
+ def find_num(lst, num):
34
+ for n in lst:
35
+ if n == num:
36
+ return True
37
+ return False
38
+ ```
39
+
40
+ The time it takes grows linearly with the size of the list, so we say it's $\mathcal{O}(n)$.
41
+
42
+ ### Big $\mathcal{O}$ Notations and Examples
43
+
44
+ Let's expand on the Big $\mathcal{O}$ topic by discussing various common Big $\mathcal{O}$ notations and providing examples for each.
45
+
46
+ #### $\mathcal{O}(1)$ - Constant Time
47
+
48
+ **Simple Explanation**: An algorithm is $\mathcal{O}(1)$ if its runtime doesn't change as the input size increases. It always takes a constant amount of time.
49
+
50
+ **Example**:
51
+ Accessing an element from an array using its index.
52
+
53
+ ```python
54
+ def get_element(arr, index):
55
+ return arr[index]
56
+ ```
57
+
58
+ #### $\mathcal{O} (\log n)$ - Logarithmic Time
59
+
60
+ **Simple Explanation**: An algorithm is $\mathcal{O} (\log n)$ if the number of operations is proportional to the logarithm of the input size. Binary search is a classic example.
61
+
62
+ **Example**:
63
+ Binary search in a sorted array.
64
+
65
+ ```python
66
+ def binary_search(arr, x):
67
+ l, r = 0, len(arr) - 1
68
+ while l <= r:
69
+ mid = (l + r) // 2
70
+ if arr[mid] == x:
71
+ return mid
72
+ elif arr[mid] < x:
73
+ l = mid + 1
74
+ else:
75
+ r = mid - 1
76
+ return -1
77
+ ```
78
+
79
+ #### $\mathcal{O}(n)$ - Linear Time
80
+
81
+ **Simple Explanation**: An algorithm is $\mathcal{O}(n)$ if its runtime grows linearly with the input size.
82
+
83
+ **Example**:
84
+ Finding the maximum value in an array.
85
+
86
+ ```python
87
+ def find_max(arr):
88
+ maximum = arr[0]
89
+ for num in arr:
90
+ if num > maximum:
91
+ maximum = num
92
+ return maximum
93
+ ```
94
+
95
+ #### $\mathcal{O}(n \log n)$ - Linear Logarithmic Time
96
+
97
+ **Simple Explanation**: Common in algorithms that divide the input in each step. Many efficient sorting algorithms have this time complexity.
98
+
99
+ **Example**:
100
+ Merge sort.
101
+
102
+ ```python
103
+ def merge_sort(arr):
104
+ if len(arr) <= 1:
105
+ return arr
106
+ mid = len(arr) // 2
107
+ left = merge_sort(arr[:mid])
108
+ right = merge_sort(arr[mid:])
109
+ return merge(left, right)
110
+
111
+ def merge(left, right):
112
+ result = []
113
+ i = j = 0
114
+ while i < len(left) and j < len(right):
115
+ if left[i] < right[j]:
116
+ result.append(left[i])
117
+ i += 1
118
+ else:
119
+ result.append(right[j])
120
+ j += 1
121
+ result.extend(left[i:])
122
+ result.extend(right[j:])
123
+ return result
124
+ ```
125
+
126
+ #### $\mathcal{O}(n^2)$ - Quadratic Time
127
+
128
+ **Simple Explanation**: Algorithms with nested loops often have a quadratic time complexity.
129
+
130
+ **Example**:
131
+ Bubble sort.
132
+
133
+ ```python
134
+ def bubble_sort(arr):
135
+ n = len(arr)
136
+ for i in range(n):
137
+ for j in range(0, n-i-1):
138
+ if arr[j] > arr[j+1]:
139
+ arr[j], arr[j+1] = arr[j+1], arr[j]
140
+ return arr
141
+ ```
142
+
143
+ #### $\mathcal{O}(2^n)$ - Exponential Time
144
+
145
+ **Simple Explanation**: Algorithms with this time complexity double their runtime with each additional input element. Recursive algorithms that solve a problem of size $n$ by recursively solving two smaller problems of size $n-1$ often have this time complexity.
146
+
147
+ **Example**:
148
+ Recursive calculation of the nth Fibonacci number.
149
+
150
+ ```python
151
+ def fibonacci(n):
152
+ if n <= 1:
153
+ return n
154
+ return fibonacci(n-1) + fibonacci(n-2)
155
+ ```
156
+
157
+ #### $\mathcal{O}(n!)$ - Factorial Time
158
+
159
+ **Simple Explanation**: Algorithms with this time complexity grow extremely fast and can become impractical even for small input sizes. Commonly seen in brute-force solutions.
160
+
161
+ **Example**:
162
+ Generating all possible permutations of a list.
163
+
164
+ ```python
165
+ def permutations(lst):
166
+ if len(lst) == 0:
167
+ return [[]]
168
+ perms = []
169
+ for i in range(len(lst)):
170
+ rest = lst[:i] + lst[i+1:]
171
+ for p in permutations(rest):
172
+ perms.append([lst[i]] + p)
173
+ return perms
174
+ ```
175
+
176
+
177
+ These are just a few examples of Big $\mathcal{O}$ notations. Understanding the time complexity of algorithms is crucial for writing efficient code and excelling in technical interviews.
178
+
179
+ ## Problem Solving
180
+
181
+ **Simple Explanation**: Problem-solving is the process of defining a problem and determining a solution to that problem.
182
+
183
+ **Example**:
184
+ Find the sum of all numbers up to a given number.
185
+
186
+ ```python
187
+ def sum_up_to_n(n):
188
+ return n * (n + 1) // 2
189
+ ```
190
+
191
+ ### The Seven Steps Tips
192
+
193
+ 1. Listen carefully what the problem is.
194
+ 2. Draw an example which serves as input and output.
195
+ 3. Come up with a brute force first. Ask yourself, what's a stupid way of doing this?
196
+ 4. Optimize the solution and make sure to spend good chunk of time here. Analyze it with space-time complexity.
197
+ 5. Walk through the algorithm before you start coding. This is like looking at a map before you start driving.
198
+ 6. Write the code. Typically the interviewer doesn't require you to run the code, but rather 2) want to hear the thought process, and 2) don't want to bogged down in syntactical details or writing surrounding classes.
199
+ 7. Veriffication. You want to verify the code and make sure it is bug-free to the best of your ability.
200
+
201
+ ### Optimizing with BUD
202
+
203
+ BUD is short for:
204
+
205
+ - B: Bottlenecks
206
+ - U: Unnecessary work
207
+ - D: Duplicated work
208
+
209
+ ### Best Conveivable Runtime
210
+
211
+ "Best conceivable runtime" is about the problem, not a specific algorithm. It has nothing to do with the best case / worst case runtime.
212
+
213
+ ## Coding
214
+
215
+ **Simple Explanation**: Coding is the act of translating a solution or algorithm into a programming language so that a computer can execute it.
216
+
217
+ **Example**:
218
+ Write code to reverse a string.
219
+
220
+ ```python
221
+ def reverse_string(s):
222
+ return s[::-1]
223
+ ```
224
+
225
+ ### Use Type Hints
226
+
227
+ Let's dive deeper into the topic of "Coding" by discussing type hints in Python.
228
+
229
+ In modern Python programming, type hints are an essential tool that enhance code readability and allow for better static type checking. Introduced in Python 3.5 through [PEP 484](https://www.python.org/dev/peps/pep-0484/), type hints provide a way to specify the expected data types of function arguments and return values. This makes it easier for developers to understand how a function should be used and can help prevent certain types of bugs.
230
+
231
+ #### Basic Type Hints
232
+
233
+ For basic data types like integers, strings, and floats, you can use the built-in Python classes as type hints.
234
+
235
+ **Example**:
236
+ ```python
237
+ def greet(name: str) -> str:
238
+ return "Hello, " + name
239
+ ```
240
+
241
+ Here, the `name` parameter is expected to be a string, and the function is also expected to return a string.
242
+
243
+ #### Lists, Dictionaries, and Other Collections
244
+
245
+ For collections, you can use the `List`, `Dict`, `Set`, and `Tuple` types from the `typing` module.
246
+
247
+ **Example**:
248
+ ```python
249
+ from typing import List, Dict
250
+
251
+ def average(numbers: List[float]) -> float:
252
+ return sum(numbers) / len(numbers)
253
+
254
+ def get_student_grades(grades: Dict[str, float]) -> List[float]:
255
+ return list(grades.values())
256
+ ```
257
+
258
+ #### Custom Types
259
+
260
+ For custom classes and data structures, you can use the class name as a type hint.
261
+
262
+ **Example**:
263
+ ```python
264
+ class Student:
265
+ def __init__(self, name: str, age: int):
266
+ self.name = name
267
+ self.age = age
268
+
269
+ def register_student(student: Student) -> None:
270
+ # Implementation here
271
+ pass
272
+ ```
273
+
274
+ #### Optional Types and None
275
+
276
+ Sometimes, a variable can be of a specific type or `None`. In such cases, you can use the `Optional` type from the `typing` module.
277
+
278
+ **Example**:
279
+ ```python
280
+ from typing import Optional
281
+
282
+ def find_student(name: str) -> Optional[Student]:
283
+ # If the student is found, return the Student object, otherwise return None
284
+ pass
285
+ ```
286
+
287
+ #### Benefits of Using Type Hints
288
+
289
+ 1. **Improved Code Readability**: Type hints make it clear what types of arguments are expected and what type of value a function will return.
290
+ 2. **Better Developer Experience**: Integrated development environments (IDEs) can use type hints to provide better auto-completions, warnings, and refactoring capabilities.
291
+ 3. **Static Type Checking**: Tools like [mypy](http://mypy-lang.org/) can be used to perform static type checking based on type hints, catching potential type-related errors before runtime.
292
+
293
+ Incorporating type hints into your Python code can greatly enhance its clarity and maintainability. While Python remains a dynamically typed language, type hints offer a way to harness some of the benefits of static typing without sacrificing the language's flexibility.
294
+
295
+ ## Verification
296
+
297
+ **Simple Explanation**: Verification involves checking that your code works correctly for all possible inputs.
298
+
299
+ **Example**:
300
+ Verify that the reverse function works.
301
+
302
+ ```python
303
+ def test_reverse_string():
304
+ assert reverse_string("hello") == "olleh"
305
+ assert reverse_string("world") == "dlrow"
306
+ ```
307
+
308
+ ## Communication
309
+
310
+ **Simple Explanation**: Communication involves explaining your thought process, your code, and any decisions you made while solving a problem.
311
+
312
+ **Example**:
313
+ "I chose a hash table for this problem because it allows for constant time lookups, which will make the solution faster."
314
+
315
+ ## Arrays
316
+
317
+ **Simple Explanation**: An array is a collection of items, where each item can be identified by an index.
318
+
319
+ **Example**:
320
+ Find the maximum value in an array.
321
+
322
+ ```python
323
+ def find_max(arr):
324
+ return max(arr)
325
+ ```
326
+
327
+ ## Strings
328
+
329
+ **Simple Explanation**: A string is a sequence of characters.
330
+
331
+ **Example**:
332
+ Check if a string is a palindrome (reads the same backward as forward).
333
+
334
+ ```python
335
+ def is_palindrome(s):
336
+ return s == s[::-1]
337
+ ```
338
+
339
+ ## Hash Tables
340
+
341
+ **Simple Explanation**: A hash table (or dictionary in Python) is a data structure that stores key-value pairs. Hash tables are a cornerstone of efficient algorithmic design, offering rapid access to data. Key attributes include:
342
+
343
+ - **Speed**: Hash tables typically allow for constant time average complexity for search operations, making data retrieval swift.
344
+ - **Key-Value Pairs**: Data is stored in key-value pairs, where each unique key maps to a specific value.
345
+ - **Collisions**: Since multiple keys might hash to the same index, handling collisions is essential. Common strategies include chaining (where each table entry references a list of all key-value pairs that hash to the same index) and open addressing (where alternative slots are sought in the array).
346
+ - **Dynamic Resizing**: To maintain efficiency, a hash table can be resized, often doubling its capacity when it's about to be filled and halving when it's less used.
347
+ - **Use Cases**: They're invaluable for tasks like data deduplication, counting distinct elements, and cache implementations.
348
+
349
+ The design and implementation of a hash table significantly influence the efficiency of algorithms that utilize it.
350
+
351
+ **Example**:
352
+ Count the frequency of each character in a string.
353
+
354
+ ```python
355
+ def char_frequency(s):
356
+ freq = {}
357
+ for char in s:
358
+ freq[char] = freq.get(char, 0) + 1
359
+ return freq
360
+ ```
361
+
362
+ ## Search
363
+
364
+ **Simple Explanation**: Searching is the process of finding a particular item in a collection.
365
+
366
+ **Example**:
367
+ Binary search in a sorted array.
368
+
369
+ ```python
370
+ def binary_search(arr, x):
371
+ l, r = 0, len(arr) - 1
372
+ while l <= r:
373
+ mid = (l + r) // 2
374
+ if arr[mid] == x:
375
+ return mid
376
+ elif arr[mid] < x:
377
+ l = mid + 1
378
+ else:
379
+ r = mid - 1
380
+ return -1
381
+ ```
382
+
383
+ ## Sorting
384
+
385
+ **Simple Explanation**: Sorting is the process of arranging items in a particular order (ascending or descending).
386
+
387
+ **Example**:
388
+ Bubble sort.
389
+
390
+ ```python
391
+ def bubble_sort(arr):
392
+ n = len(arr)
393
+ for i in range(n):
394
+ for j in range(0, n-i-1):
395
+ if arr[j] > arr[j+1]:
396
+ arr[j], arr[j+1] = arr[j+1], arr[j]
397
+ return arr
398
+ ```
399
+
400
+ ### Tips and Tricks
401
+
402
+ - Make sure you are certain and aware of the problem statement and that you are dealing with a sorting problem
403
+ - Wrtie sorting from scratch or from using builty-in sorting algorithms with multiple toolkits in your pocket
404
+ - Know not the basic sorting algorithms such as bubble sort, quick sort, and merge sort, but also know the unconventional ones such as radix sort, and bucket sort.
405
+
406
+ ### More in Sorting
407
+
408
+ Sorting is fundamental in algorithmic design, impacting data organization and processing efficiency. Key considerations include:
409
+
410
+ - **Comparison-Based**: Most classic sorting algorithms are comparison-based, meaning they work by comparing elements.
411
+ - **Stability**: A stable sort preserves the relative order of equal elements. This can be crucial in applications like database sorting.
412
+ - **In-Place**: An in-place sort uses a constant amount of extra memory (typically $\mathcal{O}(1)$).
413
+ - **Time Complexities**: Different algorithms have varied best, average, and worst-case time complexities. The choice often depends on data characteristics and specific needs.
414
+ - **Adaptivity**: Some algorithms benefit from existing order in the data, becoming faster as the input becomes more sorted.
415
+
416
+ #### **Bubble Sort**
417
+
418
+ Bubble Sort is a simple comparison-based algorithm where the largest elements "bubble" to the end of the list through successive swaps. It's inefficient for large lists, with a worst-case and average-case time complexity of $\mathcal{O}(n^2)$.
419
+
420
+ ```python
421
+ def bubble_sort(arr):
422
+ n = len(arr)
423
+ for i in range(n):
424
+ for j in range(0, n-i-1):
425
+ if arr[j] > arr[j+1]:
426
+ arr[j], arr[j+1] = arr[j+1], arr[j]
427
+ return arr
428
+ ```
429
+
430
+ #### **Merge Sort**
431
+
432
+ Merge Sort is a divide-and-conquer algorithm that splits the list in half, recursively sorts both halves, and then merges them back together. It's more efficient than Bubble Sort, with a worst-case time complexity of $\mathcal{O}(n \log n)$.
433
+
434
+ ```python
435
+ def merge_sort(arr):
436
+ if len(arr) <= 1:
437
+ return arr
438
+ mid = len(arr) // 2
439
+ left = merge_sort(arr[:mid])
440
+ right = merge_sort(arr[mid:])
441
+ return merge(left, right)
442
+
443
+ def merge(left, right):
444
+ result = []
445
+ i = j = 0
446
+ while i < len(left) and j < len(right):
447
+ if left[i] < right[j]:
448
+ result.append(left[i])
449
+ i += 1
450
+ else:
451
+ result.append(right[j])
452
+ j += 1
453
+ result.extend(left[i:])
454
+ result.extend(right[j:])
455
+ return result
456
+ ```
457
+
458
+ Both Bubble Sort and Merge Sort have their niches; the former for its simplicity and the latter for its efficiency in many scenarios.
459
+
460
+ #### **Quick Sort**
461
+
462
+ Quick Sort is a divide-and-conquer algorithm. It selects a 'pivot' element from the array and partitions the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. Quick Sort can be very fast in practice, with an average-case time complexity of $\mathcal{O}(n \log n)$, but a worst-case of $\mathcal{O}(n^2)$.
463
+
464
+ ```python
465
+ def quick_sort(arr):
466
+ if len(arr) <= 1:
467
+ return arr
468
+ pivot = arr[len(arr) // 2]
469
+ left = [x for x in arr if x < pivot]
470
+ middle = [x for x in arr if x == pivot]
471
+ right = [x for x in arr if x > pivot]
472
+ return quick_sort(left) + middle + quick_sort(right)
473
+ ```
474
+
475
+ #### **Radix Sort**
476
+
477
+ Radix Sort is a non-comparative sorting algorithm that works by distributing elements into buckets according to their individual digits. It processes the digits of each number one at a time, from the least significant digit (LSD) to the most significant digit (MSD) or vice-versa. Its time complexity is $\mathcal{O}(nk)$, where $n$ is the number of elements and $k$ is the number of passes of the sorting process.
478
+
479
+ ```python
480
+ def counting_sort_for_radix(arr, position):
481
+ size = len(arr)
482
+ output = [0] * size
483
+ count = [0] * 10
484
+
485
+ for i in range(size):
486
+ index = arr[i] // position % 10
487
+ count[index] += 1
488
+
489
+ for i in range(1, 10):
490
+ count[i] += count[i - 1]
491
+
492
+ i = size - 1
493
+ while i >= 0:
494
+ index = arr[i] // position % 10
495
+ output[count[index] - 1] = arr[i]
496
+ count[index] -= 1
497
+ i -= 1
498
+
499
+ for i in range(size):
500
+ arr[i] = output[i]
501
+
502
+ def radix_sort(arr):
503
+ max_num = max(arr)
504
+ position = 1
505
+ while max_num // position > 0:
506
+ counting_sort_for_radix(arr, position)
507
+ position *= 10
508
+ return arr
509
+ ```
510
+
511
+ #### **Bucket Sort**
512
+
513
+ Bucket Sort divides the interval of sorted values into buckets or bins. Elements are then distributed into these buckets. Each bucket is then sorted individually, either using a different sorting algorithm or recursively applying bucket sort. Its average-case time complexity is $\mathcal{O}(n + n^2/k + k)$ where $n$ is the number of elements and $k$ is the number of buckets. When $k$ is approximately $n$, the performance is close to $\mathcal{O}(n)$.
514
+
515
+ ```python
516
+ def bucket_sort(arr):
517
+ if len(arr) == 0:
518
+ return arr
519
+
520
+ min_val, max_val = min(arr), max(arr)
521
+ bucket_range = (max_val - min_val) / len(arr)
522
+ buckets = [[] for _ in range(len(arr) + 1)]
523
+
524
+ for num in arr:
525
+ buckets[int((num - min_val) / bucket_range)].append(num)
526
+
527
+ sorted_arr = []
528
+ for bucket in buckets:
529
+ sorted_arr.extend(sorted(bucket))
530
+
531
+ return sorted_arr
532
+ ```
533
+
534
+ Each of these algorithms has its strengths and is particularly suited to certain types of data or certain problem scenarios. Understanding their underlying mechanics and when to use them is a key skill in algorithm design.
535
+
536
+ ## Recursion
537
+
538
+ **Simple Explanation**: Recursion is when a function calls itself to solve smaller instances of the same problem.
539
+
540
+ **Example**:
541
+ Find the factorial of a number.
542
+
543
+ ```python
544
+ def factorial(n):
545
+ if n == 0:
546
+ return 1
547
+ return n * factorial(n-1)
548
+ ```
549
+
550
+ ### Fibonacci Number
551
+
552
+ Here's a simple recursive function to find the Fibonacci number at a given position, using type hints:
553
+
554
+ ```python
555
+ def fibonacci(n: int) -> int:
556
+ if n <= 1:
557
+ return n
558
+ return fibonacci(n-1) + fibonacci(n-2)
559
+ ```
560
+
561
+ In this function, if $n$ is 0 or 1, the function returns $n$ itself (as the 0th and 1st Fibonacci numbers are 0 and 1, respectively). For any other value of $n$, the function returns the sum of the Fibonacci numbers at positions $n-1$ and $n-2$. This is a direct application of the Fibonacci sequence definition.
562
+
563
+ However, it's worth noting that this naive recursive approach is not efficient for large values of $n$ due to the significant number of overlapping computations. For larger values, more efficient algorithms (like memoization or iterative approaches) should be considered.
564
+
565
+ ### Use Recursion to Check Whether a Number is in a Tree
566
+
567
+ Let's begin by creating the binary tree.
568
+
569
+ #### Binary Tree Class
570
+
571
+ ```python
572
+ class TreeNode:
573
+ def __init__(self, value: int) -> None:
574
+ self.value = value
575
+ self.left = None
576
+ self.right = None
577
+ ```
578
+
579
+ This `TreeNode` class represents a node in our binary tree. Each node has a `value` and two child nodes: `left` and `right`.
580
+
581
+ #### Recursive Function to Check for a Value
582
+
583
+ ```python
584
+ def contains_value(node: TreeNode, target: int) -> bool:
585
+ if not node: # If the node is None, we've reached the end without finding the value
586
+ return False
587
+ if node.value == target: # If the current node's value matches the target
588
+ return True
589
+ # Recursively check the left and right children
590
+ return contains_value(node.left, target) or contains_value(node.right, target)
591
+ ```
592
+
593
+ #### Explanation
594
+
595
+ 1. The `contains_value` function checks if a given binary tree (or subtree) contains a specific value.
596
+ 2. If the current node (`node`) is `None`, the function returns `False`, indicating that the tree doesn't contain the target value.
597
+ 3. If the value of the current node matches the target value, the function returns `True`.
598
+ 4. If neither of the above conditions is met, the function recursively checks the left and right children of the current node.
599
+
600
+ #### Usage Example
601
+
602
+ ```python
603
+ # Create a binary tree: 1
604
+ # / \
605
+ # 2 3
606
+ # / \ / \
607
+ # 4 5 6 7
608
+
609
+ root = TreeNode(1)
610
+ root.left = TreeNode(2)
611
+ root.right = TreeNode(3)
612
+ root.left.left = TreeNode(4)
613
+ root.left.right = TreeNode(5)
614
+ root.right.left = TreeNode(6)
615
+ root.right.right = TreeNode(7)
616
+
617
+ print(contains_value(root, 5)) # Output: True
618
+ print(contains_value(root, 8)) # Output: False
619
+ ```
620
+
621
+ In the example usage, we created a small binary tree and checked whether it contains the value `5` (which it does) and the value `8` (which it doesn't).
622
+
623
+ ## Stacks
624
+
625
+ **Simple Explanation**: A stack is a collection of items where the last item added is the first item removed (Last-In-First-Out).
626
+
627
+ **Example**:
628
+ Check for balanced parentheses using a stack.
629
+
630
+ ```python
631
+ def are_parentheses_balanced(s):
632
+ stack = []
633
+ mapping = {")": "(", "]": "[", "}": "{"}
634
+ for char in s:
635
+ if char in mapping:
636
+ top_element = stack.pop() if stack else '#'
637
+ if mapping[char] != top_element:
638
+ return False
639
+ else:
640
+ stack.append(char)
641
+ return not stack
642
+ ```
643
+
644
+ ### More in Stacks
645
+
646
+ Let's begin by designing the `Node` and `Stack` classes as described:
647
+
648
+ #### Node Class
649
+
650
+ This class represents an individual node in our stack. Each node has a `value` and a reference to the `next` node.
651
+
652
+ ```python
653
+ class Node:
654
+ def __init__(self, val) -> None:
655
+ self.value = val
656
+ self.next = None
657
+ ```
658
+
659
+ #### Stack Class
660
+
661
+ This class represents our stack. It has methods to `push`, `pop`, and `peek` as described.
662
+
663
+ ```python
664
+ class Stack:
665
+ def __init__(self) -> None:
666
+ self.top = None
667
+
668
+ def push(self, val) -> None:
669
+ new_node = Node(val)
670
+ new_node.next = self.top
671
+ self.top = new_node
672
+
673
+ def pop(self):
674
+ if self.top:
675
+ popped_value = self.top.value
676
+ self.top = self.top.next
677
+ return popped_value
678
+ return None
679
+
680
+ def peek(self):
681
+ return self.top.value if self.top else None
682
+ ```
683
+
684
+ #### Testing with the given array
685
+
686
+ Now, let's use the array `[1,2,3,4,5]` to test our stack:
687
+
688
+ ```python
689
+ stack = Stack()
690
+
691
+ # Pushing values onto the stack
692
+ for value in [1,2,3,4,5]:
693
+ stack.push(value)
694
+
695
+ print(stack.peek()) # Should print 5, as it's the top of the stack
696
+
697
+ # Popping values from the stack
698
+ print(stack.pop()) # Should print 5
699
+ print(stack.pop()) # Should print 4
700
+ print(stack.peek()) # Should print 3, as it's now the top of the stack
701
+ ```
702
+
703
+ When you push values onto the stack, they are added to the top. When you pop values, they are removed from the top. The `peek` method lets you see the current top value without removing it. In the context of algorithmic design, stacks are useful in various scenarios, such as evaluating expressions, implementing undo-redo functionality, and more.
704
+
705
+ ### Problem: Function Runtime
706
+
707
+ Assume we have captured information about the execution of a program: at function entry and exit we save a record which has:
708
+
709
+ - the name of the function
710
+ - the current time
711
+ - whether function starts or ends
712
+
713
+ From the sequence of records, compute the time spent in each function exclusive of time spent in called functions.
714
+
715
+ ```md
716
+ For example, given
717
+
718
+ Name operation time
719
+ A Start 0
720
+ B Start 2
721
+ B End 5
722
+ A End 6
723
+
724
+ Result: return time exclusive for each function, e.g. A: 3, B: 3
725
+ ```
726
+
727
+ #### Solution (Use Stacks)
728
+
729
+ To solve this problem, you would need to use a stack to keep track of the function calls. When a function starts, its name and start time are pushed onto the stack. When a function ends, it's popped off the stack, and the time spent on this function is calculated by subtracting the start time from the end time. To handle the exclusive time, you have to subtract the time spent in the called functions (which are tracked on the stack).
730
+
731
+ Here's a step-by-step algorithm:
732
+
733
+ 1. Initialize an empty stack and an empty dictionary to hold the result of the exclusive times for each function.
734
+ 2. Iterate through the list of records.
735
+ 3. If a record indicates that a function is starting, push it onto the stack.
736
+ 4. If a record indicates that a function is ending, pop the last function from the stack and calculate the time it ran by subtracting the start time from the current end time. Also, update the exclusive time for this function in the dictionary.
737
+ 5. If there are still functions on the stack, subtract the time of the current function from the last function on the stack to maintain the exclusive time.
738
+
739
+ Here's a sample Python function to implement this algorithm:
740
+
741
+ ```python
742
+ def calculate_exclusive_times(records):
743
+ stack = []
744
+ exclusive_times = {}
745
+
746
+ for record in records:
747
+ name, operation, time = record
748
+
749
+ if operation == 'Start':
750
+ stack.append((name, time))
751
+ elif operation == 'End':
752
+ last_function, start_time = stack.pop()
753
+ duration = time - start_time
754
+ # Initialize the key for the last function if it doesn't exist
755
+ exclusive_times[last_function] = exclusive_times.get(last_function, 0) + duration
756
+
757
+ # Adjust the exclusive time for the function currently at the top of the stack
758
+ if stack:
759
+ parent_function, _ = stack[-1]
760
+ exclusive_times[parent_function] = exclusive_times.get(parent_function, 0) - duration
761
+
762
+ return exclusive_times
763
+
764
+ # Example usage:
765
+ records = [
766
+ ('A', 'Start', 0),
767
+ ('B', 'Start', 2),
768
+ ('B', 'End', 5),
769
+ ('A', 'End', 6)
770
+ ]
771
+
772
+ calculate_exclusive_times(records)
773
+ ```
774
+
775
+ **Time Complexity:**
776
+ - The time complexity is $\mathcal{O}(n)$ where $n$ is the number of records, as we iterate through the records just once.
777
+
778
+ **Space Complexity:**
779
+ - The space complexity is $\mathcal{O}(m)$ for the stack, where $m$ is the maximum depth of function calls, and $\mathcal{O}(f)$ for the exclusive times dictionary, where $f$ is the number of unique functions. In the worst case, $m$ and $f$ could be equal to $n/2$ (if every other record is a start), so the overall space complexity can be considered $\mathcal{O}(n)$.
780
+
781
+ Let's write the function in Python and execute it with the provided example.
782
+
783
+ The Python function has computed the exclusive times for each function from the given records. The result is as expected: Function 'A' ran exclusively for 3 units of time, and Function 'B' also ran exclusively for 3 units of time.
784
+
785
+ The time complexity of this function is $\mathcal{O}(n)$, where $n$ is the number of records, because we iterate through the list of records once. The space complexity is $\mathcal{O}(m+f)$, where $m$ is the maximum depth of the function call stack at any point in time, and $f$ is the number of unique functions, which could be up to $\mathcal{O}(n)$ in the worst case if every other record is a 'Start'.
786
+
787
+ ## Queues
788
+
789
+ **Simple Explanation**: A queue is a collection of items where the first item added is the first item removed (First-In-First-Out or FIFO). It's like a line at a grocery store checkout.
790
+
791
+ **Example**:
792
+ Using Python's `queue` module to create a simple queue.
793
+
794
+ ```python
795
+ import queue
796
+
797
+ q = queue.Queue()
798
+ q.put(1)
799
+ q.put(2)
800
+ q.put(3)
801
+
802
+ # The first item to be removed will be 1
803
+ print(q.get()) # Output: 1
804
+ ```
805
+
806
+ ### Trips
807
+
808
+ - It is a first-in, first out approach. You want to process items in the order they appear.
809
+ - You want to be familiar with `.enqueue` and `.dequeue` methods.
810
+ - Be careful of how the head and tail are updated.
811
+ - Know when to use queue, linked list, stacks, etc..
812
+
813
+ ### More in Queue
814
+
815
+ Let's dive into the implementation of a `Queue` using a linked list.
816
+
817
+ #### Node Class
818
+
819
+ This class represents an individual node in our linked list. Each node has a `value` and a reference to the `next` node.
820
+
821
+ ```python
822
+ class Node:
823
+ def __init__(self, val) -> None:
824
+ self.value = val
825
+ self.next = None
826
+ ```
827
+
828
+ #### Queue Class
829
+
830
+ This class represents our queue. It has methods to `enqueue` and `dequeue` as described. We'll also implement a `__str__` method to make it easy to print the queue's contents.
831
+
832
+ ```python
833
+ class Queue:
834
+ def __init__(self) -> None:
835
+ self.front = None
836
+ self.rear = None
837
+
838
+ def enqueue(self, val) -> None:
839
+ new_node = Node(val)
840
+ if not self.rear:
841
+ self.front = self.rear = new_node
842
+ return
843
+ self.rear.next = new_node
844
+ self.rear = new_node
845
+
846
+ def dequeue(self):
847
+ if not self.front:
848
+ return None
849
+ dequeued_value = self.front.value
850
+ self.front = self.front.next
851
+ if not self.front:
852
+ self.rear = None
853
+ return dequeued_value
854
+
855
+ def __str__(self) -> str:
856
+ values = []
857
+ current = self.front
858
+ while current:
859
+ values.append(current.value)
860
+ current = current.next
861
+ return ' -> '.join(map(str, values))
862
+ ```
863
+
864
+ #### Testing with the given array
865
+
866
+ Now, let's use the array `[1,2,3,4,5]` to test our queue:
867
+
868
+ ```python
869
+ queue = Queue()
870
+
871
+ # Enqueueing values onto the queue
872
+ for value in [1,2,3,4,5]:
873
+ queue.enqueue(value)
874
+
875
+ # Dequeueing values from the queue and printing it at each step
876
+ while True:
877
+ dequeued_value = queue.dequeue()
878
+ if dequeued_value is None:
879
+ break
880
+ print(f"Dequeued: {dequeued_value}, Queue: {queue}")
881
+ ```
882
+
883
+ In this example, when values are enqueued, they are added to the rear of the queue. When values are dequeued, they are removed from the front of the queue, consistent with the First-In-First-Out (FIFO) behavior of a queue. The `__str__` method allows us to print the current state of the queue at each step.
884
+
885
+ ## Trees
886
+
887
+ **Simple Explanation**: A tree is a hierarchical data structure that consists of nodes connected by edges. The topmost node is called the root, and nodes with no children are called leaves.
888
+
889
+ **Example**:
890
+ Defining a simple binary tree.
891
+
892
+ ```python
893
+ class TreeNode:
894
+ def __init__(self, value):
895
+ self.value = value
896
+ self.left = None
897
+ self.right = None
898
+
899
+ root = TreeNode(10)
900
+ root.left = TreeNode(5)
901
+ root.right = TreeNode(20)
902
+ ```
903
+
904
+ ### Boggle Example / Find Words
905
+
906
+ To find specific valid words like "cat" from the grid, we need a dictionary or a list of valid words to cross-reference with the generated words from the grid.
907
+
908
+ For the purpose of this example, I'll assume we have a list `valid_words` that contains the word "cat". Our DFS-based function will then generate words from the grid and only return those that are present in `valid_words`.
909
+
910
+ Let's implement this:
911
+
912
+ ```python
913
+ def find_words(grid):
914
+ if not grid:
915
+ return []
916
+
917
+ rows, cols = len(grid), len(grid[0])
918
+ words = set()
919
+ valid_words = {"cat", "top"}
920
+ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up
921
+
922
+ def dfs(x, y, current_word):
923
+ if not (0 <= x < rows and 0 <= y < cols) or (x, y) in visited:
924
+ return
925
+
926
+ new_word = current_word + grid[x][y]
927
+ if new_word in valid_words:
928
+ words.add(new_word)
929
+
930
+ visited.add((x, y))
931
+
932
+ for dx, dy in directions:
933
+ dfs(x + dx, y + dy, new_word)
934
+
935
+ visited.remove((x, y))
936
+
937
+ for i in range(rows):
938
+ for j in range(cols):
939
+ visited = set()
940
+ dfs(i, j, "")
941
+
942
+ return list(words)
943
+
944
+ # Test on the provided grid
945
+ grid = [
946
+ ['c', 'a', 't'],
947
+ ['d', 'e', 'o'],
948
+ ['g', 'h', 'p']
949
+ ]
950
+
951
+ print(find_words(grid))
952
+ ```
953
+
954
+ This code will correctly identify and return the word "cat" and "top from the provided grid.
955
+
956
+ ### Count Islands (DFS)
957
+
958
+ Given a binary 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 4 islands.
959
+
960
+ ```md
961
+ Input: mat[][] = {
962
+ {1, 1, 0, 0, 0},
963
+ {0, 1, 0, 0, 1},
964
+ {1, 0, 0, 1, 1},
965
+ {0, 0, 0, 0, 0},
966
+ {1, 0, 1, 0, 0}
967
+ }
968
+ ```
969
+ The goal is to count adjst islands and islands here is defined as integer 1 that is connected together. "Connected" means left/right and top/bottom.
970
+
971
+ ```md
972
+ Expected Output: 4
973
+ ```
974
+
975
+ Hint: Define a helper function first. Then use recursion method. This should be depth first search.
976
+
977
+ Use the above information, write a python function that does it.
978
+
979
+ #### Solution
980
+
981
+ To solve this problem, we'll use Depth First Search (DFS) to traverse through the 2D matrix. Starting from each cell, we'll use DFS to explore its neighboring cells. When a cell with value `1` is visited, we'll mark it as visited and continue the DFS for its neighbors. This way, we'll traverse the entire island of connected `1`s. For every unvisited cell with value `1`, it indicates the start of a new island.
982
+
983
+ Let's write the function to solve this:
984
+
985
+ ```python
986
+ def num_islands(matrix):
987
+ if not matrix:
988
+ return 0
989
+
990
+ rows, cols = len(matrix), len(matrix[0])
991
+ visited = [[False for _ in range(cols)] for _ in range(rows)]
992
+ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up
993
+
994
+ def dfs(x, y):
995
+ if not (0 <= x < rows and 0 <= y < cols) or visited[x][y] or matrix[x][y] == 0:
996
+ return
997
+ visited[x][y] = True
998
+ for dx, dy in directions:
999
+ dfs(x + dx, y + dy)
1000
+
1001
+ count = 0
1002
+ for i in range(rows):
1003
+ for j in range(cols):
1004
+ if matrix[i][j] == 1 and not visited[i][j]:
1005
+ dfs(i, j)
1006
+ count += 1
1007
+
1008
+ return count
1009
+
1010
+ # Test with the given matrix
1011
+ mat = [
1012
+ [1, 1, 0, 0, 0],
1013
+ [0, 1, 0, 0, 1],
1014
+ [1, 0, 0, 1, 1],
1015
+ [0, 0, 0, 0, 0],
1016
+ [1, 0, 1, 0, 0]
1017
+ ]
1018
+ print(num_islands(mat))
1019
+ ```
1020
+
1021
+ The `dfs` function traverses the matrix in depth-first manner starting from a given cell `(x, y)`. If the current cell is unvisited and has a value `1`, it continues the DFS to its neighboring cells. This helps in visiting all the cells belonging to one island. The outer loop iterates over each cell and starts a DFS if it finds the start of a new island.
1022
+
1023
+ #### Time-Space Complexity
1024
+
1025
+ Let's analyze the time and space complexity of the `num_islands` function:
1026
+
1027
+ **Time Complexity**:
1028
+
1029
+ 1. **Depth First Search (DFS) Calls**: At most, every cell in the matrix will be visited once by the DFS. Therefore, the DFS contributes a time complexity of $\mathcal{O}(\text{rows} \times \text{cols})$, where `rows` is the number of rows in the matrix and `cols` is the number of columns.
1030
+ 2. **Outer Loops**: The nested loops that iterate over every cell in the matrix also contribute a time complexity of $\mathcal{O}(\text{rows} \times \text{cols})$.
1031
+
1032
+ Since both the DFS and the outer loops have the same time complexity and they don't multiply with each other (i.e., one doesn't nest inside the other), the overall time complexity of the function is $\mathcal{O}(\text{rows} \times \text{cols})$.
1033
+
1034
+ **Space Complexity**:
1035
+
1036
+ 1. **Visited Matrix**: The `visited` matrix consumes $\mathcal{O}(\text{rows} \times \text{cols})$ space.
1037
+ 2. **Recursion Stack**: In the worst case, the DFS might end up visiting all cells in the matrix due to deep recursive calls. This contributes a space complexity of $\mathcal{O}(\text{rows} \times \text{cols})$ for the call stack.
1038
+ 3. **Other Variables**: Other variables in the function (like `count`, `directions`, etc.) take constant space, which is $\mathcal{O}(1)$.
1039
+
1040
+ Considering the space taken by the `visited` matrix and the maximum potential call stack size of the DFS, the overall space complexity of the function is $\mathcal{O}(\text{rows} \times \text{cols})$.
1041
+
1042
+ In summary:
1043
+ - Time Complexity: $\mathcal{O}(\text{rows} \times \text{cols})$
1044
+ - Space Complexity: $\mathcal{O}(\text{rows} \times \text{cols})$
1045
+
1046
+ ## Heaps
1047
+
1048
+ **Simple Explanation**: A heap is a specialized tree-based data structure that satisfies the heap property. For a max heap, for any given node I, the value of I is greater than the values of its children. For a min heap, it's the opposite.
1049
+
1050
+ **Example**:
1051
+ Using Python's `heapq` module to create a min-heap.
1052
+
1053
+ ```python
1054
+ import heapq
1055
+
1056
+ heap = []
1057
+ heapq.heappush(heap, 10)
1058
+ heapq.heappush(heap, 5)
1059
+ heapq.heappush(heap, 20)
1060
+
1061
+ # The smallest item will be popped first
1062
+ print(heapq.heappop(heap)) # Output: 5
1063
+ ```
1064
+
1065
+ ### Largest Triple Products
1066
+
1067
+ You're given a list of n integers `arr[0..(n-1)]`. You must compute a list `output[0..(n-1)]` such that, for each index i (between 0 and n-1, inclusive), `output[i]` is equal to the product of the three largest elements out of `arr[0..i]` (or equal to $-1$ if $i < 2$, as `arr[0..i]` then includes fewer than three elements).
1068
+
1069
+ Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr.
1070
+
1071
+ ```md
1072
+ Example 1
1073
+ n = 5
1074
+ arr = [1, 2, 3, 4, 5]
1075
+ output = [-1, -1, 6, 24, 60]
1076
+ The 3rd element of output is 3*2*1 = 6, the 4th is 4*3*2 = 24, and the 5th is 5*4*3 = 60.
1077
+
1078
+ Example 2
1079
+ n = 5
1080
+ arr = [2, 1, 2, 1, 2]
1081
+ output = [-1, -1, 4, 4, 8]
1082
+ The 3rd element of output is 2*2*1 = 4, the 4th is 2*2*1 = 4, and the 5th is 2*2*2 = 8.
1083
+ ```
1084
+
1085
+ #### Original Solution
1086
+
1087
+ ```py
1088
+ def helper(arr):
1089
+ ans = 1
1090
+ for i in arr:
1091
+ ans = ans*i
1092
+
1093
+ return ans
1094
+
1095
+ def pick_top_3(arr):
1096
+ arr.sort()
1097
+ arr = arr[::-1]
1098
+ return arr[:3]
1099
+
1100
+
1101
+ def findMaxProduct(arr):
1102
+ # Write your code here
1103
+ if len(arr) == 0:
1104
+ return
1105
+
1106
+ if len(arr) == 1:
1107
+ return [-1]
1108
+
1109
+ if len(arr) == 2:
1110
+ return [-1, -1]
1111
+
1112
+ answer = [-1, -1]
1113
+ if len(arr) > 2:
1114
+ for i in range(2, len(arr)):
1115
+ current_array = arr[0:(i+1)]
1116
+ top_3_elements = pick_top_3(current_array)
1117
+ current_prod = helper(top_3_elements)
1118
+ answer.append(current_prod)
1119
+
1120
+ return answer
1121
+ ```
1122
+
1123
+ The code you have provided for solving the Largest Triple Products problem does not use a priority queue; rather, it uses sorting to find the top three elements at each iteration.
1124
+
1125
+ The code you have provided for solving the Largest Triple Products problem does not use a priority queue; rather, it uses sorting to find the top three elements at each iteration.
1126
+
1127
+ Here's the breakdown of the time and space complexity for your code:
1128
+
1129
+ **Time Complexity:**
1130
+
1131
+ - The main loop runs $n-2$ times, where $n$ is the length of the input array.
1132
+ - Inside the loop, you are creating a subarray `current_array` which is a $\mathcal{O}(i)$ operation.
1133
+ - Then you are sorting this subarray, which takes $\mathcal{O}(i \log i)$ time.
1134
+ - The product operation is $\mathcal{O}(1)$, since it always operates on three elements.
1135
+
1136
+ The total time complexity would be the sum of the sorting operations over all the subarrays:
1137
+
1138
+ $$T(n) = \sum_{i=3}^{n} O(i \log i)$$
1139
+
1140
+ Which can be approximated to $\mathcal{O}(n^2 \log n)$ in the worst case when $n$ is large, because the sorting time grows with the size of the subarray.
1141
+
1142
+ **Space Complexity:**
1143
+
1144
+ - The space complexity of your code is $\mathcal{O}(n)$ due to the space required for the `answer` list that stores $n$ elements.
1145
+ - Additionally, there is the space taken by the `current_array` which at most will store $n$ elements, but since it is reused and not stored persistently across iterations, it does not add to the overall space complexity.
1146
+
1147
+ #### Solution Using Priority Queue
1148
+
1149
+ Here's how you would do it:
1150
+
1151
+ - Use a min-heap to keep track of the three largest elements. The min-heap allows you to efficiently get rid of the smallest of the top three elements when you need to insert a new element into this set.
1152
+ - For each element in `arr`, insert it into the heap.
1153
+ - If the heap size exceeds three, remove the smallest element (the root of the min-heap).
1154
+ - When you have three elements in the heap, the product of these will be the required product for the current position in the output array.
1155
+ - Before you have three elements, the output is -1.
1156
+
1157
+ The time complexity of this approach would be $\mathcal{O}(n \log 3)$, which simplifies to $\mathcal{O}(n)$, since the heap operations (insertion and extraction) can be done in $\mathcal{O}(\log k)$ time, where $\mathcal{O}(k)$ is the number of elements in the heap, which is constant (3 in this case). The space complexity would be $\mathcal{O}(1)$ or $\mathcal{O}(k)$ considering the heap size is constant and does not grow with $\mathcal{O}(n)$.
1158
+
1159
+ The priority queue approach to solving the problem has been implemented in Python as follows:
1160
+
1161
+ ```python
1162
+ import heapq
1163
+
1164
+ def findMaxProduct(arr):
1165
+ # Initialize the heap and the answer array with default -1 values
1166
+ heap = []
1167
+ answer = [-1] * len(arr)
1168
+
1169
+ for i in range(len(arr)):
1170
+ # Push the current element into the heap
1171
+ heapq.heappush(heap, arr[i])
1172
+ # If the heap has more than three elements, pop the smallest one
1173
+ if len(heap) > 3:
1174
+ heapq.heappop(heap)
1175
+ # If the heap has three elements, multiply them to get the current product
1176
+ if len(heap) == 3:
1177
+ answer[i] = heap[0] * heap[1] * heap[2]
1178
+
1179
+ return answer
1180
+
1181
+ # Example usage:
1182
+ arr1 = [1, 2, 3, 4, 5]
1183
+ arr2 = [2, 1, 2, 1, 2]
1184
+ print(findMaxProduct(arr1)) # Expected output: [-1, -1, 6, 24, 60]
1185
+ print(findMaxProduct(arr2)) # Expected output: [-1, -1, 4, 4, 8]
1186
+ ```
1187
+
1188
+ When executed, the function `findMaxProduct` correctly computes the expected outputs:
1189
+
1190
+ - For the array `[1, 2, 3, 4, 5]`, the output is `[-1, -1, 6, 24, 60]`.
1191
+ - For the array `[2, 1, 2, 1, 2]`, the output is `[-1, -1, 4, 4, 8]`.
1192
+
1193
+ This implementation efficiently uses a min-heap (priority queue) to keep track of the top three elements at any point in the array, ensuring that the time complexity is `O(n)` where `n` is the length of the input array.
1194
+
1195
+ #### Try Use List
1196
+
1197
+ ```py
1198
+ def findMaxProduct(arr):
1199
+ # Write your code here
1200
+ if len(arr) == 0:
1201
+ return
1202
+
1203
+ if len(arr) == 1:
1204
+ return [-1]
1205
+
1206
+ if len(arr) == 2:
1207
+ return [-1, -1]
1208
+
1209
+ heap = []
1210
+ answer = [-1, -1]
1211
+ if len(arr) > 2:
1212
+ for i in range(len(arr)):
1213
+ heap.append(arr[i])
1214
+ if len(heap) > 3:
1215
+ heap.sort()
1216
+ heap = heap[::-1]
1217
+ heap.pop()
1218
+ if len(heap) == 3:
1219
+ answer.append(heap[0] * heap[1] * heap[2])
1220
+
1221
+ return answer
1222
+ ```
1223
+
1224
+ **Important Comment**
1225
+
1226
+ The provided function uses a list to simulate a priority queue without using the actual heap data structure provided by Python's `heapq` module. However, the way it's used in your function does not embody the efficient operations of a true heap.
1227
+
1228
+ **Time Complexity:**
1229
+
1230
+ - The main loop runs for each element in `arr`, so it has a linear component $\mathcal{O}(n)$.
1231
+ - Within the loop, you append an element to the heap, which is $\mathcal{O}(1)$ on average but can be $\mathcal{O}(n)$ in the worst case due to the need to resize the list.
1232
+ - When the heap size is greater than 3, you sort it, which is $\mathcal{O}(k \log k)$, where $\mathcal{O}(k)$ is the size of the heap. In this case, $\mathcal{O}(k)$ is at most 4, so this is a constant operation, but the constant factor is significant.
1233
+ - After sorting, you reverse the list (`heap[::-1]`), which is $\mathcal{O}(k)$.
1234
+ - The `pop` operation is $\mathcal{O}(1)$.
1235
+
1236
+ The dominant factor here is the sort operation inside the loop. Even though the heap size is small, the sort is called for every element in the array. The overall time complexity would be $\mathcal{O}(n \log k)$ with the constant $\mathcal{O}(k)$ having a relatively small impact, so we can approximate this to $\mathcal{O}(n)$, but it's important to note that the sorting makes this less efficient than a true heap implementation.
1237
+
1238
+ **Space Complexity:**
1239
+
1240
+ - The space complexity for the `heap` list is $\mathcal{O}(1)$ since it stores at most 3 elements.
1241
+ - The `answer` list is $\mathcal{O}(n)$ since it stores an element for each input in `arr`.
1242
+
1243
+ So, the space complexity of the function is $\mathcal{O}(n)$.
1244
+
1245
+ **Is it a heap structure?**
1246
+
1247
+ No, the structure you are using is not a heap. A heap is a specialized tree-based data structure that satisfies the heap property: if $P$ is a parent node of $C$, then the key (the value) of $P$ is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of $C$. The node at the "top" of the heap (the root node) has the greatest value in a max heap or the smallest in a min heap.
1248
+
1249
+ In your function, you are enforcing this property manually by sorting the list every time it exceeds a size of 3. This does ensure that the largest (or smallest) element is always at a specific position in the list, but it does not provide the same performance guarantees as a heap. A true heap structure allows you to insert and extract elements in $\mathcal{O}(\log n)$ time, which is not the case with your list-based approach since the sort operation is more costly.
1250
+
1251
+
1252
+ ## Graphs
1253
+
1254
+ **Simple Explanation**: A graph is a collection of nodes (or vertices) and edges that connect these nodes. It can be used to represent many real-world systems like networks, roads, etc.
1255
+
1256
+ **Example**:
1257
+ Representing a simple undirected graph using an adjacency list.
1258
+
1259
+ ```python
1260
+ graph = {
1261
+ 'A': ['B', 'C'],
1262
+ 'B': ['A', 'D', 'E'],
1263
+ 'C': ['A', 'F'],
1264
+ 'D': ['B'],
1265
+ 'E': ['B', 'F'],
1266
+ 'F': ['C', 'E']
1267
+ }
1268
+ ```
1269
+
1270
+ ## Greedy Algorithms
1271
+
1272
+ **Simple Explanation**: Greedy algorithms make locally optimal choices at each step with the hopes of finding a global optimum. They don't always guarantee the best solution, but they are often fast and good for optimization problems.
1273
+
1274
+ **Example**:
1275
+ The coin change problem. Given coins of certain denominations and a total amount, find the minimum number of coins that make up that amount.
1276
+
1277
+ ```python
1278
+ def coin_change(coins, amount):
1279
+ coins.sort(reverse=True)
1280
+ count = 0
1281
+ for coin in coins:
1282
+ if amount == 0:
1283
+ break
1284
+ num_coins = amount // coin
1285
+ count += num_coins
1286
+ amount -= coin * num_coins
1287
+ return count if amount == 0 else -1
1288
+
1289
+ print(coin_change([1, 2, 5], 11)) # Output: 3 (5 + 5 + 1)
1290
+ ```
1291
+
1292
+ ---
1293
+
1294
+ These are the additional sections you've requested. Integrating them with the previous content would yield a comprehensive guide on many of the fundamental topics in computer science and algorithms.
1295
+
1296
+ This markdown file provides an overview of common topics in software engineering interviews. It's important to practice and understand the underlying principles behind each topic to succeed in interviews.
1297
+ """
1298
+ )