-
Notifications
You must be signed in to change notification settings - Fork 4
/
practice-algos-python.txt
800 lines (653 loc) · 27.2 KB
/
practice-algos-python.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# Coin change ============================================================================
# Summary:
# - initialize a list of size amount + 1 to store the minimum qty amounts
# - for every coin, for every amount (represented by each index of list), store the minimum in that index between what's already there and list[that index value - coin] + 1
# - each index in the list will represent the least number of coins necessary to reach that index value.
# - return list[amount]
def coinChange(self, coins: [int], amount: int) -> int:
# function header describes variables + their type. (var : type)
# -> int indicates return type
# Bottom-up approach, recurrence relation: finding the minimum coins
# needed for every value up till the final amount.
# key points:
# - the minimum qty of coins needed for a given (amount value) is equal to the minimum qty of coins needed for (amount value - C) + 1, where C is the last coin added to equal the amount value. This makes sense since you are taking off one coin to the amount value, this means that if you add this coin, it will take 1 more total qty of coins.
# - thus, we need to find the minimum qty of coins for each incremental amount leading up to the amount value we are looking for by comparing the minimum qty of coins that could be obtained from each C in the list.
# more intuition: say your amount = 11, and coins = [1,2,5]. Then if your "last coin" is 1, then the remaining amount occupied by the other X number of coins is 10. You can then check what the minimum amount of coins is needed to obtain 10, etc. until the smallest coin value, and then repeat this process for coin '2' and '5'. (In the code, we do this the other way around, starting from the smallest coin value)
###################################### CODE BELOW ######################################
# creating a list to store the number of coins needed for each incremental amount
# float('inf') is a python code to indicate big value. The list will be of size amount+1 filled with 'inf'. The 'inf' will be replaced with smallest qty needed for each amount value. The amount value is indicated by the index of the elements in the list. It goes up to amount + 1 since we must account for the 0 index (amount+1's index nb = amount)
dp = [float('inf')] * (amount + 1)
dp[0] = 0
# for each coin as last coin picked, find the minimum qty of coins needed for each amount value (which is indicated by index)
# for loop over coins first so that we don't have to deal with negatives since x>=coin is guaranteed in the second loop.
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
# Linked List Cycle: determining if there is a cycle
# slower: change the value in each node, if re-encounter it, return true
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
temp = header
while temp.next is not None:
if temp.val == float('inf'):
return True
temp.val = float('inf')
temp = temp.next
return False
# faster: use two pointers to race each other, one jumps faster so will loop around if cycle exists.
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
# two pointers
ptr1 = head
ptr2 = head.next
while ptr2.next is not None and ptr2.next.next is not None:
if ptr1 == ptr2:
return True
ptr1 = ptr1.next
ptr2 = ptr2.next.next
return False
# REVERSE LINKED LIST =====================================
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# version 1: changing values not actual nodes, using stack O(n)
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return head
stack = []
temp = head
temp2 = head
while temp is not None:
stack.append(temp.val)
temp = temp.next
while head is not None:
head.val = stack.pop()
head = head.next
return temp2
# version 2 iterative: changing node positions. O(n) time and O(1) space
def reverseList(self, head: ListNode) -> ListNode:
# Summary: retrieve each element in the list one by one from left to right and link them to each other in a 'separate list' to invert
# the list nodes order.
# -keep track of 'prev' element which always points to the head of the reversed list
# -almost as if we are making a separate list. the 'prev' starts at null since it's the last element of the inverted list.
# -we update 'prev' each time by linking to it the next element in the list, then setting 'prev' to this new element as it's now
# the head of inverted list.
# -while doing this, we use 'temp' to store the reference to the rest of the list, and curr = temp moves the pointers forward.
curr = head
prev = None
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp # -> curr = curr.next
return prev
# version 2 recursive: start from the end and link each node to it's previous one. think of it as the nodes at the end are already
# reversed so now how do you reverse the n-1 linkage.
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
newHead = self.reverseList(head.next) # don't forget "self" since func not defined yet
head.next.next = head # linking next node to previous! pointer manipulation
head.next = None
return newHead
# MERGE TWO SORTED LIST ============================================================
# similar to merge sort: compare the elements from the two list and link the smallest to the new linked list node.
# -> must advance the pointers in the first list, second list and also resulting list.
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode() # new linked list (head will be placeholder, actually starts at head.next)
temp = head
# iterate until one of the two list is done
while l1 is not None and l2 is not None:
if l1.val < l2.val:
temp.next = l1 # ok to set directly because l1 already moved from previous iteration
l1 = l1.next # increment 1st list pointer
else:
temp.next = l2
l2 = l2.next # increment 2nd list pointer
temp = temp.next #increment result list pointer
# attach the remainder list
temp.next = l1 if l1 is not None else l2
return head.next
# BUY AND SELL STOCK ===================================================================
# brute force: O(n^2)
# iterate over array, for each element, check the other ones
# if the next element is larger than element AND larger than previous, store this value
# at the end of each iteration, compute maximum profit for that var, (0 if negative)
# return max profit
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
max = 0
# for each value, update max 'sell' value, then compare profit with previous
for i in range(0, len(prices)):
for j in range(i+1, len(prices)):
if prices[j] > prices[i] and prices[j] > max:
max = prices[j]
# if profit greater than previous, update
if maxProfit < max - prices[i]:
maxProfit = max - prices[i]
max = 0
return maxProfit if maxProfit > 0 else 0
# One-Pass: Keep track of minimum buy value & max profit, equivalent
# to the smallest valley followed by the max peak. O(n)
# key: sell must be after buy, so previous elements don't matter if they didn't work
# Since only the sell must be after buy, we can directly iterate over and store the
# minimum buy value. If the value after it is smaller, than we can directly update.
# If the value after is greater, then we can directly compute new maxProfit and see if
# it's greater than the previous one. (If a given value Y has not provided us with
# a max profit up until the value X, and X is smaller than Y, then we can simply give
# up on Y and check for max profit with X for the rest of the array.)
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minValue = float('inf')
for price in prices:
if price < minValue:
minValue = price
elif maxProfit < price - minValue:
maxProfit = price - minValue
return maxProfit
# RANGE SUM QUERY - IMMUTABLE ==================================================================
# function to get sum of values in given range repetitively.
class NumArray:
# If the sumRange function is used repetitively on similar ranges, we would have to
# re-compute same values multiple times. Instead, we can use prefix sum to cache the
# sums up till a given index, and simply subtract to return the sum in a given range.
def __init__(self, nums: List[int]):
self.numArray = nums
# compute prefix sum
for i in range(1, len(nums)):
self.numArray[i] = nums[i] + nums[i-1]
def sumRange(self, i: int, j: int) -> int:
if i == 0:
return self.numArray[j]
else:
return self.numArray[j] - self.numArray[i-1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
# PALINDROME ===========================================
# fastest
def isPalindrome(self, s: str) -> bool:
if s == "":
return True
st = "".join(char for char in s if char.isalnum()).lower()
# indexes the string, -1 indicates reverse [start:end:step]
# st[::-1] returns the reversed string. fastest because no external
# function calls, directly uses slicing which is highly optimized.
return st == st[::-1]
# slower
def isPalindrome(self, s: str) -> bool:
if s == "":
return True
# strip the string of non-alpha chars
strg = re.sub("[^a-z0-9]", "", s.lower())
if strg[i] != strg[len(strg)-1-i]:
return False
return True
# MERGE INTERVALS ================================================
# need to create a separate 'merged' list to return.
# sort the intervals by their first element.
# once sorted, the intervals which need to be merged will be contiguous.
# then we can simply check if the next interval's first element is bigger or not.
# if bigger, simply add to list, if smaller or equal, merge!
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# sort the intervals by 1st element:
intervals.sort(key=lambda x: x[0])
# merged intervals result list
merged = [intervals[0]]
# check if next interval's starting element is larger or not
for interval in intervals:
# if larger, no need to merge, so simply add to resulting list
if interval[0] > merged[-1][1]:
merged.append(interval)
# if smaller or equal, then merge with the one already in resulting list
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
# MAXIMUM SUBARRAY ==================================================
def maxSubArray(self, nums: List[int]) -> int:
# sliding window (find negative nb)
# if positive = keep adding
# 3 scenarios:
# 1. max subarray sum is the value currently stored in maxSum
# 2. max subarray includes the new found negative nb (counter += nb)
# 3. max subarray is the one which comes after the new found negative nb (counter = 0)
# if negative = reset a counter to 0, since there may be a bigger subarray but only
# after the negative nb OR with the negative number
# keep track of the max sum so far as well as the sum from after the negative nb.
maxSum, counter = nums[0], 0
for nb in nums:
if counter < 0:
counter = 0
counter += nb
maxSum = max(maxSum, counter)
return maxSum
# CISCO ASSESSMENT =====================================================
# Q1:
matrix = []
size = int(raw_input())
for i in range(0, size):
# this splits a string into list of nbs, then converts all nbs into integers.
nbs = map(int, str(raw_input()).split())
matrix.append(nbs)
# this rotates matrix by 90 degrees clockwise
matrix = list(list(x)[::-1] for x in zip(*matrix))
for i in range(0, size):
for j in range(0, size):
print matrix[i][j],
print
# Q2: 3D MATRIX IN PYTHON
size = int(input())
# row starting with white and black
wRow = []
bRow = []
for i in range(0,size):
wRow.append("W" if i % 2 == 0 else "B")
bRow.append("W" if (i+1) % 2 == 0 else "B")
# board
board = []
count = 0
for i in range(0, size):
if count % 2 == 0:
board.append(wRow)
else:
board.append(bRow)
count += 1
# Print
for i in range(0, len(board)):
for j in range(0, len(board[i])):
print(board[i][j], end=" ")
print()
# FLIPPING MATRIX
def rotate_90_degree_anticlckwise(matrix):
new_matrix = []
for i in range(len(matrix[0]), 0, -1):
new_matrix.append(list(map(lambda x: x[i-1], matrix)))
return new_matrix
def rotate_90_degree_clckwise(matrix):
new_matrix = []
for i in range(len(matrix[0])):
li = list(map(lambda x: x[i], matrix))
li.reverse()
new_matrix.append(li)
return new_matrix
def rotate_90_degree_clckwise_by_zip_method(matrix):
return list(list(x)[::-1] for x in zip(*matrix))
# https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
# Check if nb is odd or even BITWISE OPERATOR
if nb & 1:
return 'odd'
else:
return 'even'
# email regex
if re.search("^[a-zA-Z0-9_.]+@[a-z-]+\.com|net|org$", word):
print("true")
else:
print("false")
def numDuplicates(name, price, weight):
# Write your code here
dict = {}
count = 0
for (n, p, w) in zip(name, price, weight):
if (n, p, w) in dict:
count += 1
dict[(n, p, w)] = 1
return count
# TRAPPING RAIN WATER =======================================================
"""
- Squarepoint Capital
[Brute force O(n^2)]
For each element in list:
- find the max left and right pillar height
- take the minimum of the two
- from that minimum, minus the height of the current spot.
This will give you the nb of raindrops in the current spot.
Don't forget to discard negatives when incrementing the total output.
"""
def trap(self, height: List[int]) -> int:
if not height:
return 0
counter = 0
max_left = height[0]
max_right = height[len(height)-1]
# iterate over each spot
for i in range(1, len(height)-1):
# check max left pillar height
for l in range(1, i):
if height[l] > max_left:
max_left = height[l]
# check max right pillar height
for r in range(i+1, len(height)-1):
if height[r] > max_right:
max_right = height[r]
# get current spot raindrop nb
add = min(max_left, max_right) - height[i]
if add > 0:
counter += add
max_left = height[0]
max_right = height[len(height)-1]
return counter
# Make The String Great ==================================
"""
- also got brute force method with recursion 2 pass on leetcode.
- use stack instead to check last index element.
"""
def makeGood(self, s: str) -> str:
stack = []
for ch in s:
if stack and stack[-1] == ch.swapcase():
stack.pop()
else:
stack.append(ch)
return "".join(stack)
# MAX DEPTH OF BINARY TREE
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
left = self.maxDepth(root.left) + 1
right = self.maxDepth(root.right) + 1
return max(left,right)
# MISSING NUMBER IN ARRAY
def missingNumber(self, nums: List[int]) -> int:
sum = ((len(nums)-1)*((len(nums)-1)+1))/2
count = 0
for i in nums:
count += i
return int(count - sum + 1)
# VALIDATE BINARY SEARCH TREE
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
bst = []
self.inorder(root, bst)
return all(bst[i] > bst[i-1] for i in range(1, len(bst)))
def inorder(self, root, bst):
if root is None:
return
self.inorder(root.left, bst)
bst.append(root.val)
self.inorder(root.right, bst)
# LOWEST COMMON ANCESTOR BINARY SEARCH TREE
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return root
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
# 211 DESIGN ADD AND SEARCH WORDS DATA STRUCTURE
"""
You used a dictionary and a set. The optimal solution requires a Trie.
Trie: tree with each node containing a hashmap<Character, Node> and a boolean. Each node links to another node until word is finished.
"""
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
# Used dictionary to append: (length of word, [list of word of this length])
self.data = {}
# Used set to checked if word already added.
self._set = set()
# Time complexity: O(1)
def addWord(self, word: str) -> None:
if word in self._set or not word.isalpha() or any(x.isupper() for x in word):
return
if len(word) not in self.data:
self.data[len(word)] = [word]
else:
self.data[len(word)].append(word)
self._set.add(word)
# Time complexity: O(d*w) -> where d is number of dots in word and w number of words of same length.
# -> Looping through word of same length
def search(self, word: str) -> bool:
if any(x.isupper() for x in word) or len(word) not in self.data:
return False
if "." in word:
word_list = self.data[len(word)]
for w in word_list:
if re.search("^" + word + "$", w):
return True
else:
return True if word in self._set else False
return False
# SYMMETRIC TREE
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.isMirror(left.left, right.right) and self.isMirror(left.right, right.left)
# kTH SMALLEST ELEMENT IN A BST
def kthSmallest(self, root: TreeNode, k: int) -> int:
if root is None:
return -1
def inorder(root, arr):
if root is None:
return
inorder(root.left, arr)
arr.append(root.val)
inorder(root.right, arr)
arr = []
inorder(root, arr)
return arr[k-1]
# MINIMUM DEPTH OF A BINARY TREE
# O(n), faster if use if statements and prevent calls for Nones
# must use both max and min, in case of linked list type trees (if
# only one sided.)
def minDepth(self, root: TreeNode) -> int:
if root is None:
return 0
if None in [root.left, root.right]:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
# BINARY TREE RIGHT SIDE VIEW
"""
Getting the right most value of each level of the tree.
- Use a dictionary to store the depth as the key and the
value as the value in each node.
- Use pre-order traversal, so that the value for each depth updates
towards the right, and the most right nodes are the ones staying at the end.
The nodes which have higher depth will not be overwritten and will stay when
converting dictionary to list.
"""
def rightSideView(self, root: TreeNode) -> List[int]:
right = {}
def see_right(root, d):
if root is None:
return
right[d] = root.val
see_right(root.left, d + 1)
see_right(root.right, d + 1)
see_right(root, 0)
return right.values()
# BFS implementation
"""
Remember the dequeue stack.. pop from the start (left) so that it's
BFS! Pop from the top of stack so that it's DFS.
"""
def rightSideView(self, root):
if root is None:
return []
# create dequeue to allow O(1) from both ends
deq = collections.deque()
deq.append(root)
result = []
while deq:
size, val = len(deq), 0
for i in range(size):
# pop left since BFS
node = deq.popleft()
if node.left:
deq.append(node.left)
if node.right:
deq.append(node.right)
val = node.val
result.append(val)
return result
# RANGE SUM QUERY
class NumArray:
"""
Initialize an additional array to hold blocks of size sqrt(n), where n is size of original list.
These blocks would be the sums of those sqrt(n) nb of elements. We would then use these blocks
to perform range sum queries to avoid having to iterate over each element to sum. O(sqrt(n))
- Keep in mind we still need original array to perform sums on the two blocks on the end, since
the picked index range could be a number in the middle of the block.
"""
def __init__(self, nums: List[int]):
# nums: original array
# blocks_len: total length of blocks array
# blocks: blocks array
self.nums = nums
block_size = math.sqrt(len(nums))
self.blocks_len = int(math.ceil(len(nums) / block_size))
self.blocks = [0] * self.blocks_len
for i in range(len(nums)):
self.blocks[i // self.blocks_len] += nums[i]
"""
- Update block array value
- Update original array value
"""
def update(self, index: int, val: int) -> None:
block_index = index // self.blocks_len
self.blocks[block_index] = self.blocks[block_index] - self.nums[index] + val
self.nums[index] = val
"""
2 scenarios:
- If in same block
- If in different blocks
"""
def sumRange(self, left: int, right: int) -> int:
start_block = left // self.blocks_len
end_block = right // self.blocks_len
sum = 0
if start_block == end_block:
# means the indices are contained inside one block, just iterate and add.
for i in range(left, right +1):
sum += self.nums[i]
else:
# for left-most block. Convert the block index to the actual index!
for i in range(left, (start_block + 1) * self.blocks_len):
sum += self.nums[i]
# for blocks in between
for i in range(start_block + 1, end_block):
sum += self.blocks[i]
# for right-most block
for i in range(end_block * self.blocks_len, right +1):
sum += self.nums[i]
return sum
# AVERAGE LEVEL BINARY TREE
def averageOfLevels(self, root: TreeNode) -> List[float]:
if root is None:
return
yeet = []
que = collections.deque()
que.append(root)
sum = 0
while que:
size = len(que)
for i in range(size):
node = que.popleft()
sum += node.val
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
yeet.append(sum / size)
sum = 0
return yeet
# MEDIUM: ROTTING ORANGES
"""
BFS
- The minimum number of minutes needed to rot all oranges is essentially the number of
iterations needed to obtain the shortest path between the starting point and the
furthest away fresh orange.
- It's why this can be computed with both DFS and BFS.
- With BFS, we can find the number of iterations for the shortest path simply by incrementing.
- With DFS, we can find this minimum number by finding the max depth of recursion of the search.
"""
def orangesRotting(self, grid: List[List[int]]) -> int:
"""
- Find the rotten oranges and place their indices in a queue.
- Find the number of fresh oranges.
- If there are none: finish.
- Else, start BFS with the queue of rotten orange indices.
- For each rotten orange, rot their neighbours.
- Can check if neighbouring indices are out of bounds with a coordinates array.
- Increment a count during each iteration.
- Finish if either all oranges are rotted or if nb of fresh oranges reaches 0.
"""
if not grid:
return -1
fresh_count = 0
# queue of rotten orange indices
que = collections.deque()
for i in range(len(grid)):
for k in range(len(grid[i])):
if grid[i][k] == 2:
que.append((i,k))
elif grid[i][k] == 1:
fresh_count += 1
if fresh_count == 0:
return 0
minutes = 0
# coordinates
check = [(-1, 0), (1, 0), (0, 1), (0, -1)]
# BFS
while que and fresh_count:
size = len(que)
minutes += 1
for i in range(size):
orange = que.popleft()
for coord in check:
row = orange[0] + coord[0]
col = orange[1] + coord[1]
# if new index exists and is a fresh orange, rot it and put in queue
if row >= 0 and row < len(grid) and col >= 0 and col < len(grid[row]) and grid[row][col] == 1:
grid[row][col] = 2
que.append((row, col))
fresh_count -= 1
return minutes if fresh_count == 0 else -1
# DFS
"""
Iterate through the matrix and dfs on each cell.
Increment the minutes integer each time you dfs.
The max depth of the dfs minus two is the minimum number of minutes needed.
This works too because the depth of the DFS to an end is a "shortest path". This
value will be the same as when doing BFS since their results both reflect the "shortest path".
Time: O(M*N) -> Row * Columns. Each cell is traversed max two times.
Space: O(M*N): if only one case is rotten at a corner and all else are fresh. Big recursion!
"""
def orangesRotting(self, grid: List[List[int]]) -> int:
for i in range(len(grid)):
for k in range(len(grid[i])):
if grid[i][k] == 2:
self.dfs(grid, i, k, 2)
min = 2
for i in range(len(grid)):
for k in range(len(grid[i])):
if grid[i][k] == 1:
return -1
min = max(min, grid[i][k])
return min-2
def dfs(self, grid, i, k, min):
# check if out of bounds indices, empty, or rotten by anohter
if i < 0 or k < 0 or i >= len(grid) or k >= len(grid[i]) or grid[i][k] == 0 or (grid[i][k] < min and grid[i][k] >= 2):
return
grid[i][k] = min
self.dfs(grid, i+1, k, min+1)
self.dfs(grid, i-1, k, min+1)
self.dfs(grid, i, k+1, min+1)
self.dfs(grid, i, k-1, min+1)