-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblems.py
4378 lines (3818 loc) · 163 KB
/
problems.py
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################
# CATEGORIZATION:
##################
# I Categorize my past problems into sets to make it easier to find them via simple query later.
# E.g: to find all problems of difficultly 'easy' which use a 'tree' data structure:
# find(diff.easy, ds.tree)
# E.g to find all problems I've completed this month:
# find_by_date(months_ago=0)
# It also allows me to print some statistics about problems that I've been working on for motivation.
# E.g:
# 19/08/16 Fri:
# Total Problems solved: 65
# Problems solved in recent days: 1 0 0 0 0 0 1 0 0 0 0 4 2 0 0 0 0 3 0 0 1 2 1 1 0 3 1 0 0 1
# Problems solved in recent weeks: 1 5 5 8 2 10 11 4 1 3
# Problems solved in recent Months: 8 34 8 10
# Difficulty of problems: Easy:29 Medium: 27 Hard: 9
# Data Structures stats
# arrays 16 hashtable 14 tree 14 stacks 10 graph 8 heaps 6 linked_list 4 queue 2
# Time stats
# min_30 21 hour_2 13 min_15 11 hour_5 8 hour 6 days 2
# Sources stats
# hackerrank 45 leetcode 15 misc_interview_questions 2 reddit 1
# Process finished with exit code 0
class SetStats:
"""Designed to be a parent class, so that you can get nice stats from child classes."""
@classmethod
def _get_all_count(cls):
"""
:rtype dict
Print Statistics about problems solved via:
for key, value in CLASS._get_all_count().iteritems():
print " ", key, value
"""
members = filter(lambda x : x[0:1] != "_", dir(cls))
d = dict()
for member in members:
d[member] = getattr(cls, member)
for member_type in d.keys():
d[member_type] = len(d[member_type])
return d
class ds(SetStats): # DataStructures.
tree = set()
graph = set()
arrays = set()
stacks = set()
queue = set()
linked_list = set()
hashtable = set()
heaps = set()
class algo: # Algorithms
dfs_bfs = set() # Problems that could be solved either way.
bfs = set() # BFS specific problems, e.g nearest path problems.
bisect = set()
search = set()
mst = set()
kruskal = set()
dynamic = set()
class diff: # Difficulty.
easy = set()
med = set()
hard = set()
class time(SetStats): # rounded to nearest. Note, this is the time it took *me* to solve them, rather than an estimate for you :-).
min_15 = set()
min_30 = set()
hour = set()
hour_2 = set()
hour_5 = set()
days = set()
class tag(SetStats):
optimization = set() # Problems where it may be common to implement O(n^2) but better solutions are available.
interview_material = set() # Good problem to use for interviewing people or teaching.
non_interview = set() # Problems not likley to be asked on interviews due to their length/complexity.
insight = set() # Problem that required some out-of-the-box thinking.
random_test = set() # Problem for which I wrote random tests
recursion = set() # A problem that has a recursive solution.
failed = set() # Problems I've tried and failed at. Maybe do some other day.
amazon = set() # Problem (or kinda-like it) was asked on an Aamzon interview.
strings = set() # Lots of work with String data.
math = set() # Problems involving match. E.g series.
interesting = set() # Problems that just interest me. (as of 19/07/30). Cool/funky problems.
class source(SetStats):
hackerrank = set()
leetcode = set()
reddit = set()
misc_interview_questions = set() # Random interview questions I've bumped into. Often don't have tests or detailed description.
instacart = set()
problem_categories = [ds, algo, diff, time, tag]
all_problems = set() # dynamically populated set with all problems I've worked on. (or those added via addto(..))
from datetime import date, timedelta
prob_dates = []
from collections import namedtuple
Date_and_func = namedtuple("Date_and_func", ["date", "func"])
from itertools import product
def addto(problem, *args):
for arg in args:
if isinstance(arg, date):
prob_dates.append(Date_and_func(arg, problem.__name__))
elif isinstance(arg, set):
arg.add(problem)
all_problems.add(problem)
################
################ Problems
################
# Leet code uses typing in it's Solution signatures:
from typing import List, Set, Tuple, Dict
# ######## Templates:
def __():
pass
def merge_kSortedLists():
# URL: https://leetcode.com/problems/merge-k-sorted-lists/submissions/
# see also: https://www.geeksforgeeks.org/merge-k-sorted-arrays/
# Intuition:
# Convert into regular lists
# Use heapq.merge which uses a min-heap internally to merge lists. -> O(n k Log k)
# Convert back to Linked list.
# Alternative solution is to merge them in order. (1st & 2nd, then merge result with 3rd, then with 4th etc...)
# Runtime: 128 ms, faster than 52.95% of Python3 online submissions for Merge k Sorted Lists.
# Memory Usage: 20.7 MB, less than 6.06% of Python3 online submissions for Merge k Sorted Lists.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
import heapq
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
normal_lists = []
for ll in lists:
lst = []
curr = ll
while curr:
lst.append(curr.val)
curr = curr.next
normal_lists.append(lst)
sorted_list = heapq.merge(*normal_lists)
head = None
curr = None
for i in sorted_list:
if head is None:
head = ListNode(i)
curr = head
else:
curr.next = ListNode(i)
curr = curr.next
return head
addto(merge_kSortedLists, ds.heaps, diff.med, date(2019,9,12), time.min_15, source.leetcode,)
def heap__kthLargest():
# Inuition: Use a min-heap. Replace top element if new element *is bigger*. Return what's left on the heap.
# 5a44c60be8684dd7906618899bb10931
# Runtime: 76 ms, faster than 80.34% of Python3 online submissions for Kth Largest Element in an Array.
# Memory Usage: 15 MB, less than 10.00% of Python3 online submissions for Kth Largest Element in an Array.
from typing import List
from heapq import heappush, heapreplace
class Solution:
def findKthLargest(self, nums, k) -> int:
mheap = []
for i in nums:
if len(mheap) < k:
heappush(mheap, i)
else:
if i > mheap[0]:
heapreplace(mheap, i)
return mheap[0]
# 1 line solution:
import heapq
def findKthLargest(self, nums, k) -> int:
return heapq.nlargest(k, nums)[-1]
addto(heap__kthLargest, ds.heaps, diff.med, time.min_15, date(2019,9,12), source.leetcode, tag.interview_material)
def Array__BestTimeToBuyAndSellStock():
# URL:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# Find the biggest increase.
# Intuitivley, keep track of current min and find the biggest difference.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
curr_min = prices[0]
max_diff = 0
for i in prices:
if i < curr_min:
curr_min = i
continue
else:
diff = i - curr_min
max_diff = max(max_diff, diff)
return max_diff
addto(Array__BestTimeToBuyAndSellStock, ds.arrays, diff.easy, time.min_15, date(2019,8,16), source.leetcode, tag.interview_material)
def Hashtable__HashDS_with_timestamps():
# URL: https://www.glassdoor.ca/Interview/Problem-broken-into-three-phases-1-create-a-hash-like-data-structure-class-that-handles-get-and-set-2-Allow-key-to-ho-QTN_3147006.htm
# Software Engineer Interview
# Problem broken into three phases
# 1. create a hash like data structure class that handles get and set.
# 2. Allow key to hold many values with each value having a timestamp. if get receives just they key, return latest value. If get receives both key and time, return the appropriate value.
# 3. modify get to return closest value with timestamp lesser than argument timestamp.
from collections import defaultdict, OrderedDict
from time import time
from bisect import bisect_left, bisect
class DictTimeStamps:
def __init__(self):
self.dic_vals = defaultdict(list)
self.dic_times = defaultdict(list)
def set(self, key, val, timestamp=None):
if timestamp is None:
timestamp = time()
if timestamp in self.dic_times[key]: # Overwrite an existing timestamp.
ts_index = self.dic_times[key].index(timestamp)
self.dic_vals[key][ts_index] = val
else:
self.dic_vals[key].append(val)
self.dic_times[key].append(timestamp)
return timestamp
def get(self, key, timestamp=None):
if key not in self.dic_vals:
raise KeyError
if timestamp is None:
return self.dic_vals[key][-1]
else:
if timestamp in self.dic_times[key]:
indx = bisect_left(self.dic_times[key], timestamp)
else:
indx = bisect(self.dic_times[key], timestamp) - 1
return self.dic_vals[key][indx]
dts = DictTimeStamps()
ts0 = dts.set(1, "a")
ts1 = dts.set(1, "b")
dts.set(1, "c", ts1)
dts.set(1, "z")
print(dts.get(1)) # exp: z
print(dts.get(1, ts0)) # exp: a
dts.set(2, "val1", 5)
dts.set(2, "val2", 10)
print(dts.get(2, 7)) # exp: "val1"
addto(Hashtable__HashDS_with_timestamps, ds.hashtable, algo.bisect, diff.med, time.hour, date(2019,8,10), source.instacart, tag.interview_material, tag.interesting)
def LinkedLists__MergeTwoLinkedLists():
# URL: https://leetcode.com/problems/merge-two-sorted-lists/
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Solution: Create new list. (Alternative, merge l2 into l1)
# Runtime: 44 ms, faster than 63.71% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 13.9 MB, less than 5.08% of Python3 online submissions for Merge Two Sorted Lists.
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = None
curr = None
while l1 or l2:
if l1 and l2:
if l1.val < l2.val:
val = l1.val
l1 = l1.next
else:
val = l2.val
l2 = l2.next
elif l1:
val = l1.val
l1 = l1.next
else:
val = l2.val
l2 = l2.next
if head is None:
head = ListNode(val)
curr = head
else:
curr.next = ListNode(val)
curr = curr.next
return head
addto(LinkedLists__MergeTwoLinkedLists, ds.linked_list, time.min_30, diff.easy, date(2019,8,5), source.leetcode, tag.interview_material, tag.amazon)
def Hashmap__ThreeSumAdv():
# O(n^2) with optimizations.
# Intuition:
# (I use i,j,k instead of a,b,c)
# - nested i,j loop to produce every possible (i,j) in O(n^2) time.
# - for each i,j, check if nums contains a k such that k is after j. Using a dict, this is O(1)
# - This is accomplished by keeping a dictionary that keeps the last index of any given value.
# - to keep output tuples unique
# - use a set to store output (automatically deduplicates) -> O(1)
# - sort tuple's i,j,k and use the tuple as key ot the set.
# - Last test case is very large [0,0,0,0,0,0....0]. It times out.
# We observe that tuple consists of 3 elements, so remove any number that occurs more than 3 times.
# Runtime: 724 ms, faster than 87.02% of Python3 online submissions for 3Sum.
# Memory Usage: 18.1 MB, less than 5.46% of Python3 online submissions for 3Sum.
from collections import defaultdict
class Solution:
def threeSum(self, nums_in: List[int]) -> List[List[int]]:
# Optimization: Don't permit more than 3 duplicates
nums_count = defaultdict(int)
nums = []
for n in nums_in:
nums_count[n] += 1
if nums_count[n] <= 3:
nums.append(n)
# Keep track of last index of any given number. (i + j + want = 0)
num_last_i = dict()
for i, n in enumerate(nums):
num_last_i[n] = i
out = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
want = - (nums[i] + nums[j]) # i+j+w=0 -> w = -(i+j)
if want in num_last_i:
last_w_i = num_last_i[want]
if last_w_i > j:
out_tup = tuple(sorted([nums[i], nums[j], nums[last_w_i]]))
out.add(out_tup)
return [list(o) for o in out]
res = Solution().threeSum([-1, 0, 1, 2, -1, -4])
print("[")
for l in res:
print(" ", l)
print("]")
# Brute force:
# O(n^3) -> Time Limit Exceeded. Can you do better?
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
out = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
for k in range(j + 1, len(nums)):
ival, jval, kval = nums[i], nums[j], nums[k]
if (ival + jval + kval) == 0:
out.add(tuple(sorted([ival, jval, kval])))
return [list(o) for o in out]
addto(Hashmap__ThreeSumAdv, ds.hashtable, diff.med, time.hour_2, date(2019,8,5), source.leetcode, tag.amazon, tag.interesting, tag.interview_material)
def Graph__MultiDFS_NumberOfIslands():
# URL:https://leetcode.com/problems/number-of-islands/submissions/
very_similar_to = Graphs__MultiBFS_maxRegion() # except here only up/down/left/right. Easier to code up.
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid) == 0 or len(grid[0]) == 0:
return 0
rows = len(grid)
cols = len(grid[0])
island_count = 0
for row in range(rows):
for col in range(cols):
cell = grid[row][col]
if cell == "1":
island_count += 1
grid[row][col] = "0" # mark as visited when adding to queue.
to_explore = [(row, col)]
while to_explore:
r, c = to_explore.pop()
for near_r, near_c in [(r, c - 1), (r - 1, c), (r, c + 1), (r + 1, c)]:
if 0 <= near_r < rows and 0 <= near_c < cols:
if grid[near_r][near_c] == "1":
grid[near_r][near_c] = "0"
to_explore.append((near_r, near_c))
return island_count
addto(Graph__MultiDFS_NumberOfIslands, ds.graph, algo.bfs, algo.dynamic, diff.med, time.min_30, date(2019,8,5), source.leetcode, tag.interesting, tag.interview_material)
def Search__LongestPalidromicSubstring():
# URL: https://leetcode.com/problems/longest-palindromic-substring
# Dynamic Programming (supposedly?)
# Approach: Expand Around Center
# Time: O(n^2)
# Space: O(1)
# Better: Manacher's Algo. O(n). But too complex for 45 mins.
# https://www.hackerrank.com/topics/manachers-algorithm
class Pali:
def __init__(self, i, j):
self.i = i
self.j = j
self.diff = j - i
def expand_center(s, lower, upper):
while (lower - 1) >= 0 and (upper + 1) < len(s) and \
s[lower - 1] == s[upper + 1]:
lower, upper = lower - 1, upper + 1
return Pali(lower, upper)
class Solution:
def longestPalindrome(self, s: str) -> str:
if s == "":
return ""
mx_pali = Pali(0, 0)
for i in range(len(s)):
odd_pali = expand_center(s, i, i)
if (i + 1) < len(s) and s[i] == s[i + 1]:
even_pali = expand_center(s, i, i + 1)
else:
even_pali = Pali(0, 0)
mx_pali = max(mx_pali, odd_pali, even_pali, key=lambda p: p.diff)
return s[mx_pali.i: mx_pali.j + 1]
s = Solution()
tests = [["babad", "bab"],
["cbbd", "bb"],
["zgeegf", "geeg"],
["zgefegfr", "gefeg"],
["", ""]]
results = []
for t, e in tests:
res = s.longestPalindrome(t)
results.append(res)
print(res == e, t, e, res)
print("::", all(results))
# Alternative (2x slower but easier? to read) solution would be to insert "#" between everything. aba -> #a#b#a#
# so no ambiguity about palindrome position.
# Runtime: 2504 ms, faster than 45.47% of Python3 online submissions for Longest Palindromic Substring.
# Memory Usage: 13.9 MB, less than 22.89% of Python3 online submissions for Longest Palindromic Substring.
# ...
class Solution:
def longestPalindrome(self, s: str) -> str:
if s == "":
return ""
s = "".join(["#", "#".join(s), "#"])
mx = Pali(0, 0)
for i in range(len(s)):
pali = expand_center(s, i, i)
mx = max(mx, pali, key=lambda p: p.diff)
pali_str = s[mx.i: mx.j + 1]
pali_str = "".join([c if c != "#" else "" for c in pali_str])
return pali_str
# ...
addto(Search__LongestPalidromicSubstring, ds.arrays, algo.dynamic, diff.med, time.hour, date(2019,8,5), source.leetcode, tag.interesting, tag.amazon, tag.optimization)
def OrderedDict__LRU_Cache():
# URL: https://leetcode.com/problems/lru-cache/
# 54e9b14946354840b9292408008bf7af
# Solution that extends OrderedDict() itself:
# Runtime: 208 ms, faster than 77.37% of Python3 online submissions for LRU Cache.
# Memory Usage: 23 MB, less than 5.45% of Python3 online submissions for LRU Cache.
from collections import OrderedDict
class LRUCache(OrderedDict): # Extend OrederdDict instead of initiating local copy.
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key in self:
self.move_to_end(key)
return self[key]
else:
return -1
def put(self, key: int, value: int) -> None:
self[key] = value
self.move_to_end(key)
if len(self) > self.capacity:
del (self[next(iter(self.keys()))])
# Solution that adds self.d=OrderedDict()
# Runtime: 204 ms, faster than 88.32% of Python3 online submissions for LRU Cache.
# Memory Usage: 22.9 MB, less than 5.45% of Python3 online submissions for LRU Cache.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.d = OrderedDict()
self.capacity = capacity
def get(self, key: int) -> int:
if key in self.d:
self.d.move_to_end(key)
return self.d[key]
else:
return -1
def put(self, key: int, value: int) -> None:
# Consider case where we overwrite a key. Key needs to move to front.
self.d[key] = value
self.d.move_to_end(key)
if len(self.d) > self.capacity:
del (self.d[next(iter(self.d))])
#-------- Testing code:
def leet_test(funcs, args, expected, test_name=""): # Leet code test runner.
"""Class testing code"""
obj, overall = eval(funcs[0] + "(" + str(args[0])[1:-1] + ")"), True
print(test_name + " ", obj.__class__.__name__)
for i in range(1, len(funcs)):
arg, exp = str(args[i])[1:-1], expected[i]
cmd = "{}.{}({})".format("obj", funcs[i], str(arg))
res = eval(cmd)
if res != exp: overall = False
print("{:<5} {:<15} arg:{:<5} res:{:<5} exp:{:<5}".format(str(res == exp), str(cmd), str(arg), str(res), str(exp)))
print("::", overall, "\n")
null = None # Leetcode tends to use 'null'
if __name__ == '__main__':
leet_test( # l1: funcs to call. l2: args. l3: expc out
["LRUCache", "get", "put", "get", "put", "put", "get", "get"],
[[2], [2], [2, 6], [1], [1, 5], [1, 2], [1], [2]],
[null, -1, null, -1, null, null, 2, 6]
#
)
leet_test(
["LRUCache", "put", "put", "put", "put", "get", "get"],
[[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]],
[null, null, null, null, null, -1, 3]
# out[null, null, null, null, null, 1, -1]
# state? 2=1 2=1,1=1 1=1,2=3 2=3,4=1
)
'''
Input
["LRUCache","put","put","put","put","get","get"]
[[2],[2,1],[1,1],[2,3],[4,1],[1],[2]]
Output
[null,null,null,null,null,1,-1]
Expected
[null,null,null,null,null,-1,3]
'''
'''
Failing
Input
["LRUCache","get","put","get","put","put","get","get"]
[[2],[2],[2,6],[1],[1,5],[1,2],[1],[2]]
Output
[null,-1,null,-1,null,null,2,-1]
Expected
[null,-1,null,-1,null,null,2,6]
'''
''' Working test:
Your input
["LRUCache","put","put","get","put","get","put","get","get","get"]
[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
Output
[null,null,null,1,null,-1,null,-1,3,4]
Expected
[null,null,null,1,null,-1,null,-1,3,4]
'''
addto(OrderedDict__LRU_Cache, ds.hashtable, diff.med, time.hour_2, date(2019,8,4), source.leetcode, tag.amazon, tag.interesting, tag.insight)
def LinkedList__AddTwoNumbers():
# URL: https://leetcode.com/problems/add-two-numbers/submissions/
# Given two linked lists, where a node hold a single digit, reversed,
# add both numbers and return a reversed list.
# Testing:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Solution 1: Convert list to integers.
# This sol is a bit more intuitive.
# Runtime: 84 ms, faster than 31.32% of Python3 online submissions for Add Two Numbers.
# Memory Usage: 14 MB, less than 5.20% of Python3 online submissions for Add Two Numbers
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def ll_to_num(lst):
num = []
curr = lst
while curr:
num.append(curr.val)
curr = curr.next
num.reverse()
return int("".join(map(str, num)))
def num_to_ll(num):
reversed_digits = list(map(int, str(num)[::-1]))
head = ListNode(reversed_digits[0])
curr = head
for i in reversed_digits[1:]:
curr.next = ListNode(i)
curr = curr.next
return head
n1 = ll_to_num(l1)
n2 = ll_to_num(l2)
return num_to_ll(n1 + n2)
# Solution 2: Traverse both lists in parallel.
# This solution uses less memory and arguably does less work.
# Runtime: 68 ms, faster than 97.55% of Python3 online submissions for Add Two Numbers.
# Memory Usage: 13.9 MB, less than 5.20% of Python3 online submissions for Add Two Numbers.
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = None
carry = 0
while l1 or l2 or carry != 0:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
nsum = l1_val + l2_val + carry
val = nsum % 10
carry = nsum // 10
if head is None:
head = ListNode(val)
curr = head
else:
curr.next = ListNode(val)
curr = curr.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return head
""" Testing:
[2,4,3]
[5,6,4]
-> [7,0,8]
[1,8]
[0]
-> [1,8]
[5]
[5]
-> [0, 1]
"""
addto(LinkedList__AddTwoNumbers, ds.linked_list, diff.easy, time.min_30, date(2019,8,4), source.leetcode, tag.amazon)
def Hashtable__Find_Majority():
# URL: https://leetcode.com/problems/majority-element/submissions/
# Attempt 4: (Review of other people's code:
# Runtime: 192 ms, faster than 79.52% of Python3 online submissions for Majority Element.
# Memory Usage: 14.9 MB, less than 5.11% of Python3 online submissions for Majority Element.
from collections import Counter
class Solution:
def majorityElement(self, nums):
counts = Counter(nums)
return max(counts, key=counts.get)
# Simmilar to counter, except with default dict.
from collections import defaultdict
class Solution:
def majorityElement(self, nums):
d = defaultdict(int)
for i in nums:
d[i] += 1
return max(d, key=d.get)
# Attempt 3:
# O(n) solution.
# Count instances via hash table O(n). Find max value in the hashtable O(k) (where k = # of unique keys)
# Runtime: 196 ms, faster than 65.03% of Python3 online submissions for Majority Element.
# Memory Usage: 15.2 MB, less than 5.43% of Python3 online submissions for Majority Element.
from collections import defaultdict
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
d = defaultdict(int)
for i in nums:
d[i] += 1
max_val = -1
max_key = None
for i in d.keys():
if d[i] > max_val:
max_val = d[i]
max_key = i
return max_key
# Attempt 2
# O (n log n)
# Sort. Traverse. Track element counts. Return max counts.
# Runtime: 204 ms, faster than 38.62% of Python3 online submissions for Majority Element.
# Memory Usage: 15 MB, less than 5.43% of Python3 online submissions for Majority Element.
from collections import defaultdict
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
curr_i = None
max_element = None
max_count = 0
for i in nums:
if curr_i is None or i != curr_i:
curr_i = i
curr_count = 1
else:
curr_count += 1
if curr_count > max_count:
max_count = curr_count
max_element = i
return max_element
# Attemp 1
# O(n log n)
# Count items via hashtable. Sort Hash table according to key count. O (k log k), where k=unique keys.
# Runtime: 192 ms, faster than 79.88% of Python3 online submissions for Majority Element.
# Memory Usage: 15.3 MB, less than 5.43% of Python3 online submissions for Majority Element.
from typing import List
from collections import defaultdict
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counts = defaultdict(int)
for i in nums:
counts[i] += 1
count_list = list(counts.items())
count_list.sort(key=lambda x: x[1])
return count_list[-1][0]
addto(Hashtable__Find_Majority, ds.hashtable, time.min_30, diff.easy, source.leetcode, tag.interview_material, tag.interesting, tag.optimization)
def Array__TwoSum__IceCreamVersion():
# URL: https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem
# O(n)
def whatFlavors(cost, money):
seen = dict()
for i in range(len(cost)):
flavor_cost = cost[i]
remaining = money - flavor_cost
if remaining in seen:
print(seen[remaining], i + 1)
else:
seen[flavor_cost] = i + 1
addto(Array__TwoSum__IceCreamVersion, ds.hashtable, diff.easy, time.min_15, date(2019, 7, 30), source.hackerrank, tag.interview_material)
def Search__Triple_tuple():
# URL: https://www.hackerrank.com/challenges/triple-sum/problem
# Given arrays A,B,C find count of (p,q,r), such that p<= q >= r. (duplicates, unsorted).
# !/bin/python3
# f1b36e7abb66483cba6fefb551a676bb
# O(a log a + b log b + c log c)
def triplets(a, b, c):
a, b, c = [list(set(i)) for i in [a, b, c]] # Deduplicate.
a.sort()
b.sort()
c.sort()
tuple_count = 0
ai, ci = 0, 0 # a_index, c_index
for b_val in b:
while a[ai] < b_val:
if ai < len(a) - 1 and a[ai + 1] <= b_val: # Consider [1,4,10..] not increments of 1.
ai += 1
else:
break
if a[ai] > b_val:
continue
while c[ci] < b_val:
if ci < len(c) - 1 and c[ci + 1] <= b_val:
ci += 1
else:
break
if c[ci] > b_val:
continue
tuple_count += (ai + 1) * (ci + 1)
return tuple_count
### Same solution, but more concise:
def triplets(A, B, C):
A, B, C = [sorted(set(i)) for i in [A, B, C]] # Deduplicate & sort.
tuple_count = 0
def move_up(L, li, b):
while L[li] < b and li < len(L) - 1 and L[li + 1] <= b:
li += 1
return li
ai, ci = 0, 0 # a_index, c_index
for b in B:
ai = move_up(A, ai, b)
ci = move_up(C, ci, b)
if A[ai] > b or C[ci] > b:
continue
tuple_count += (ai + 1) * (ci + 1)
return tuple_count
####
# O(a log a + b log b + c log c + b log a + b logc)
# Slower solution but easier to implement/write. Still passes all test cases.
#...
from bisect import bisect
def triplets(A, B, C):
A, B, C = [list(set(i)) for i in [A, B, C]] # Deduplicate.
A.sort()
B.sort()
C.sort()
tuple_count = 0
for b in B:
ai = bisect(A, b) # A=[2,3,4], b[5] -> ai = 3. b[1]-> 0
bi = bisect(C, b)
if ai == 0 or bi == 0:
continue
tuple_count += ai * bi
return tuple_count
# ..
addto(Search__Triple_tuple, ds.arrays, algo.search, diff.med, time.hour_2, date(2019,7,30), source.misc_interview_questions, tag.interview_material, tag.insight, tag.interesting)
def Search__Permutated_Substrings():
# URL: --- Found brief mention on youtube.
# Given s and b, find all permutations of s in b.
s = "xacxzaa"
b = "fxaazxacaaxzoecazxaxaz"
# More simple:
# s = aabc
# b = aacbacab
#
# Attempt 1: (Works but slow).
# O(bs). For every substring, compare dictionary.
from collections import Counter
def find_permutated_substrings(needle, haystack):
s_counted = Counter(needle)
out = []
for i in range(len(haystack) - len(needle)):
substr = haystack[i:i + len(needle)]
substr_counted = Counter(substr)
if s_counted == substr_counted:
out.append(substr)
return out
print(find_permutated_substrings(s, b))
# Attempt 2: (Fast but buggy).
# O(b). Generate prime numbers & assign to characters. Maintain running prime_sum.
# If running prime sum is same as s prime sum, it's a permutation.
# -> Works-ish, but unreliable.
# (seems to have minor bug that rarely shows up, probably summing primes generates ambiguity/conflict. e.g 2+5=7).
from collections import deque
def find_permutated_substrings_prime(needle, haystack):
def prime_generator(): # pg = prime_generator(); next(pg)
first_100_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109,
113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,
523, 541]
for p in first_100_primes:
yield p
call_count = 1
i = first_100_primes[-1] + 1
while True:
i += 1
for j in range(2, i):
if i % j == 0:
break
else:
print(call_count)
call_count += 1
yield i
char_to_prime = dict()
pg = prime_generator() # Optimization: Pre-compute primes.
# Assign primes to unique characters in input.
for chr in needle + haystack:
if chr not in char_to_prime:
char_to_prime[chr] = next(pg)
s_prime_sum = sum([char_to_prime[c] for c in needle])
out = []
stream = deque()
running_prime_sum = 0
for i in range(len(haystack)):
stream.append(haystack[i])
running_prime_sum += char_to_prime[haystack[i]]
if len(stream) > len(needle):
left_char = stream.popleft()
running_prime_sum -= char_to_prime[left_char]
if running_prime_sum == s_prime_sum:
out.append("".join(stream))
return out
print(find_permutated_substrings_prime(s, b))
# Attempt 3: (Fast and reliable)
# O(n)
# Have a streaming dictionary, starting with negative counts of s. (e.g aabc -> a=-2, b=-1, c=-1).
# Add/remove characters from stream. If len(dict) == 0, we have a match.
from collections import Counter, deque, defaultdict
def find_permutated_substrings_streamingdict(s, b):
# s = "abc"
# b = "acbaacb"
# s = aabc
# b = aacbacab -> 4 matches.
dictstream = Counter(s)
for k in dictstream.keys():
dictstream[k] = -dictstream[k]
charstream = deque()
out = []
for c in b:
charstream.append(c)
dictstream[c] += 1
if dictstream[c] == 0:
del (dictstream[c])
if len(charstream) > len(s):
popped = charstream.popleft()
dictstream[popped] -= 1
if dictstream[popped] == 0:
del (dictstream[popped])
if len(dictstream) == 0:
out.append("".join(charstream))
return out
print(find_permutated_substrings_streamingdict(s, b))
# Tests and comparisons:
import random
import string
s = "".join([random.choice(string.ascii_lowercase) for _ in range(1000)])
b = "".join([random.choice(string.ascii_lowercase) for _ in range(100000)])
print("p1")
r1 = find_permutated_substrings(s, b)
print("p2")
r2 = find_permutated_substrings_prime(s, b)
print("p3")
r3 = find_permutated_substrings_streamingdict(s, b)
# Most of the time r1==r2==r3, although there seems to be a subtle situation where they sometimes off by 1?. Meh.
if r1 == r2 == r3:
print("Equal", len(r1))
else:
print("Not equal", len(r1), len(r2), len(r3))
import timeit
print(find_permutated_substrings.__name__, timeit.timeit(lambda: find_permutated_substrings(s, b), number=5))
print(find_permutated_substrings_prime.__name__, timeit.timeit(lambda: find_permutated_substrings_prime(s, b), number=5))
print(find_permutated_substrings_streamingdict.__name__, timeit.timeit(lambda: find_permutated_substrings_streamingdict(s, b), number=5))
# Performance Analysis.
# Very big performance difference if s is large. (1000+)
# find_permutated_substrings 24.026676302 O(sb)
# find_permutated_substrings_prime 0.3006969350000013 O(b)
# find_permutated_substrings_streamingdict 0.6048754650000028 O(b)
addto(Search__Permutated_Substrings, ds.hashtable, diff.med, time.hour_2, date(2019,7,30), source.misc_interview_questions, tag.insight, tag.interview_material, tag.interesting)
def Graphs__TopologicalSort_CourseScheduling():
# Time: O(N + E)
# Space: O(N) #DFS stack.
# Alternative: Node Indegree
# 01651c3d70d74c76812d8ee54e25dcfa Notability/notes.
# Solution with class + pointers. Most readable.
# Runtime: 112 ms, faster than 90.15%-27% of Python3 online submissions for Course Schedule II.
# Memory Usage: 15 MB, less than 51.44% of Python3 online submissions for Course Schedule II.
from enum import Enum, auto
class Col(Enum): # Py>=3.4. Slower than regular int comparison, but makes debuging a lot easier. -> Worth using.
White = auto() # New
Gray = auto() # Visiting (DFS in progress)
Black = auto() # Visited
class Node:
def __init__(self, id):
self.id = id
self.edges = list()
self.col = Col.White