-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode.py
More file actions
1682 lines (1442 loc) · 52.1 KB
/
Copy pathLeetCode.py
File metadata and controls
1682 lines (1442 loc) · 52.1 KB
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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def printLstNode(self, lstNode):
for i in range(len(lstNode)):
print(lstNode[i].val)
def printLinkedList(self, node):
while node:
print(node.val)
node = node.next
def createLinkedList(self, lstVal):
head = ListNode(lstVal[0])
tmpHead = head
for i in range(1, len(lstVal)):
tmpHead.next = ListNode(lstVal[i])
tmpHead = tmpHead.next
return head
def addTwoNumbers(self, l1, l2):
curL1 = l1
curL2 = l2
carry = 0
totalNode = [] # you can just use a dummy head
count = 0
while(curL1 or curL2):
if not curL1:
total = curL2.val + carry
curL2 = curL2.next
elif not curL2:
total = curL1.val + carry
curL1 = curL1.next
else:
total = curL1.val + curL2.val + carry
curL1 = curL1.next
curL2 = curL2.next
carry = total // 10
newNode = ListNode(total % 10)
totalNode.append(newNode)
if count != 0:
totalNode[-2].next = totalNode[-1]
count += 1
if (carry != 0):
newNode = ListNode(carry)
totalNode[-1].next = newNode
return totalNode[0]
def lengthOfLongestSubstring(self, s):
if len(s) == 1:
return len(s)
substring = []
Max = 0
for sub in s:
print(sub)
if sub in substring:
if (len(substring) > Max):
Max = len(substring)
if (substring.index(sub) != len(substring) - 1):
substring = substring[substring.index(sub) + 1:]
else:
substring = []
substring.append(sub)
else:
substring.append(sub)
if len(substring) > Max:
return len(substring)
return Max
def findMedianSortedArrays(self, nums1, nums2):
if len(nums1) >= len(nums2):
B = nums1
A = nums2
else:
A = nums1
B = nums2
m = len(A)
n = len(B)
imin, imax = 0, m
while(imin <= imax):
i = (imin + imax) // 2
j = (m + n - 2 * i) // 2
if i > 0 and A[i - 1] > B[j]:
imax = i - 1
elif j > 0 and B[j - 1] > A[i]:
imin = i + 1
else:
if i == 0:
max_left = B[j - 1]
elif j==0:
max_left = A[i - 1]
else:
max_left = max(A[i - 1], B[j - 1])
if (m + n) % 2 == 1:
return max_left
if i == m: min_right = B[j]
elif j == n: min_right = A[i]
else: min_right = min(A[i], B[j])
return (max_left + min_right) / 2.0
def convert(self, s, numRows):
total = []
for i in range(numRows):
total.append([])
pointer = 0
reachBottom = False
total[0].append(s[0])
for c in s[1:]:
if not reachBottom:
pointer += 1
total[pointer].append(c)
if pointer == numRows - 1:
reachBottom = True
else:
pointer -= 1
total[pointer].append(c)
if pointer == 0:
reachBottom = False
result = []
for i in range(numRows):
result = result + total[i]
result = ''.join(result)
return result
def isMatch(self, s, p):
if not p:
return not s
match = bool(s) and (p[0] == '.' or p[0] == s[0])
if len(p) >= 2 and p[1] == '*':
return self.isMatch(s, p[2:]) or match and self.isMatch(s[1:], p)
else:
return match and self.isMatch(s[1:], p[1:])
def maxArea(self, height):
maximum = 0
start = 0
end = len(height) - 1
changeLeft = True
while start != end:
least = min((height[start], height[end]))
area = least * (end - start)
if area > maximum:
maximum = area
if changeLeft:
start += 1
changeLeft = False
else:
end -= 1
changeLeft = True
return maximum
def letterCombinations(self, digits):
# You can use dictionary
lst = list('abcdefghijklmnopqrstuvwxyz')
seperateLst = []
index = 0
for i in range(0, 8):
if i == 5 or i == 7:
num_ch = 4
else:
num_ch = 3
tempLst = []
for j in range(0, num_ch):
tempLst.append(lst[index])
index += 1
seperateLst.append(tempLst)
dialLst = []
for c in digits:
digit = int(c)
dialLst.append(seperateLst[digit - 2])
result = []
index = 0
def backtrack(combination, next_digit):
if not next_digit:
result.append(combination)
else:
for i in seperateLst[int(next_digit[0]) - 2]:
backtrack(combination + i, next_digit[1:])
if digits:
backtrack("", digits)
return result
def reverseKGroup(self, head, k):
newhead = head
index = 0
ifReplaced = False
while newhead != None:
if (index+1) % k == 0:
# do reverse
lstNode = []
tmpnext = newhead.next
if not ifReplaced:
tmphead = head
while (tmphead != newhead):
lstNode.append(tmphead)
tmphead = tmphead.next
tmphead = tmphead.next
tmptmphead = newhead
for i in range(len(lstNode), 0, -1):
tmptmphead.next = lstNode[i - 1]
tmptmphead = tmptmphead.next
tmptmphead.next = tmpnext
if not ifReplaced:
ifReplaced = True
head = newhead
print('tmphead val: ' + str(lstNode[-1].val))
index += 1
newhead = newhead.next
return head
def trap(self, height):
if len(height) == 0:
return 0
left_max = [0] * len(height)
rignt_max = [0] * len(height)
area = 0
left_max[0] = height[0]
rignt_max[-1] = height[-1]
for i in range(1, len(height)):
left_max[i] = max(left_max[i - 1], height[i])
for i in range(len(height) - 1, 1, -1):
rignt_max[i - 1] = max(rignt_max[i], height[i - 1])
for i in range(1, len(height)):
area += min(left_max[i], rignt_max[i]) - height[i]
return area
def _dfs(self, grid, r, c):
n_row = len(grid)
n_col = len(grid[r])
grid[r][c] = '0'
if r - 1 >= 0 and grid[r - 1][c] == '1': self._dfs(grid, r - 1, c)
if r + 1 < n_row and grid[r + 1][c] == '1': self._dfs(grid, r + 1, c)
if c - 1 >= 0 and grid[r][c - 1] == '1': self._dfs(grid, r, c - 1)
if c + 1 < n_col and grid[r][c + 1] == '1': self._dfs(grid, r, c + 1)
def numIslands(self, grid):
if len(grid) == 0:
return 0
n_islands = 0
for i in range(len(grid[0])):
for j in range(len(grid)):
if grid[j][i] == '1':
self._dfs(grid, j, i)
n_islands += 1
return n_islands
def mergeTwoLists(self, l1, l2):
prevHead = ListNode(-1)
prev = prevHead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1 if l1 is not None else l2
return prevHead.next
def num_islands(self, grid):
def _dfs(self, grid, r, c):
n_row = len(grid)
n_col = len(grid[r])
grid[r][c] = '0'
if r + 1 <= n_row and grid[r + 1][c] == '1': self._dfs(grid, r + 1, c)
if c + 1 <= n_col and grid[r][c + 1] == '1': self._dfs(grid, r, c + 1)
if len(grid) == 0:
return 0
n_islands = 0
for i in range(len(grid[0])):
for j in range(len(grid)):
if grid[j][i] == '1':
self._dfs(grid, j, i)
n_islands += 1
print(grid)
return n_islands
def zigzag_level_order(self, root):
if not root:
return []
answer = []
self._helper(answer, root, 0, True)
return answer
def _helper(self, answer, root, depth, direction):
if not root:
return
if len(answer) == depth:
answer.append([])
if not direction:
answer[depth].append(root.val)
if direction:
answer[depth].insert(0, root.val)
self._helper(answer, root.right, depth + 1, not direction)
self._helper(answer, root.left, depth + 1, not direction)
def kClosest(self, points, k):
dist = lambda i: points[i][0]**2 + points[i][1]**2
def sort(i, j, k):
if i >= j: return
K = (i + j) // 2
points[i], points[K] = points[K], points[i]
mid = partition(i, j)
if k < mid - i + 1:
sort(i, mid - 1, k)
elif k > mid - i + 1:
sort(mid + 1, j, k - (mid - i + 1))
def partition(i, j):
oi = i
pivot = dist(i)
i += 1
while True:
while i < j and dist(i) < pivot:
i += 1
while i <= j and dist(j) >= pivot:
j -= 1
if i >= j: break
points[i], points[j] = points[j], points[i]
points[oi], points[j] = points[j], points[oi]
return j
sort(0, len(points) - 1, k)
return points[:k]
def mostCommonWord(self, paragraph, banned):
import re
bag_words = re.findall(r'\w+', paragraph.lower())
frequency = {}
max_freq = 0
answer = ""
for word in bag_words:
if word in banned: continue
if not (word in frequency):
frequency[word] = 1
else:
frequency[word] += 1
if frequency[word] > max_freq:
max_freq = frequency[word]
answer = word
return answer
def isSubtree(self, mainTree, subTree):
def equal(mainTree, subTree):
if mainTree is None and subTree is None:
return True
if mainTree is None or subTree is None:
return False
return (mainTree.val == subTree.val and
equal(mainTree.left, subTree.left) and
equal(mainTree.right, subTree.right))
def traverse(mainTree, subTree):
return mainTree != None and (equal(mainTree, subTree) or
traverse(mainTree.left, subTree) or
traverse(mainTree.right, subTree))
return traverse(mainTree, subTree)
def partitionLabels(self, s):
# get the last index of each char
last = {c: i for i, c in enumerate(s)}
ans = []
anchor = j = 0
for i, c in enumerate(s):
j = max(j, last[c])
if i == j:
ans.append(i - anchor + 1)
anchor = i + 1
return ans
def longestPalindrome(self, s):
table = [[0 for i in range(len(s))]for j in range(len(s))]
ans = ""
for j in range(len(s) - 1, 0 - 1, -1):
for i in range(j, len(s)):
table[i][i] = True
table[i][j] = s[j] == s[i] and (i - j < 3 or table[i - 1][j + 1])
if table[i][j] and i - j + 1 > len(ans):
ans = s[j:i+1]
return ans
def prisonAfterNDays(self, cells, N):
def getNextDay(cells):
return [int(i > 0 and i < (len(cells) - 1) and cells[i-1] == cells[i+1])
for i in range(len(cells))]
seen = {}
while N > 0:
c = tuple(cells)
if c in seen:
N = N % (seen[c] - N)
seen[c] = N
cells = getNextDay(cells)
if N >= 1:
N -= 1
return cells
def maxProfit(self, prices):
min_price = max(prices)
max_diff = 0
min_index = len(prices) - 1
for i, price in enumerate(prices):
if price < min_price:
min_price = price
min_index = i
if i > min_index and price - min_price > max_diff:
max_diff = price - min_price
return max_diff
def hasPath(self, maze, start, destination):
visited = [[False for i in range(len(maze[0]))]for j in range(len(maze))]
def dfs(maze, start, destination, visited):
if visited[start[0]][start[1]]:
return False
if start == destination:
return True
visited[start[0]][start[1]] = True
r, l, u, d = start[1] + 1, start[1] - 1, start[0] - 1, start[0] + 1
while(r < len(maze[0]) and maze[start[0]][r] == 0): # right
r += 1
if dfs(maze, [start[0], r - 1], destination, visited):
return True
while(l >= 0 and maze[start[0]][l] == 0): # left
l -= 1
if dfs(maze, [start[0], l + 1], destination, visited):
return True
while(d < len(maze) and maze[d][start[1]] == 0):
d += 1
if dfs(maze, [d - 1, start[1]], destination, visited):
return True
while(u >= 0 and maze[u][start[1]] == 0):
u -= 1
if dfs(maze, [u + 1, start[1]], destination, visited):
return True
return False
return dfs(maze, start, destination, visited)
def ladderLength(self, beginWord, endWord, wordList):
from collections import defaultdict
if endWord not in wordList or not beginWord or not endWord or not wordList:
return 0
all_combo_dict = defaultdict(list)
L = len(beginWord)
# Prepare a look a table for the word list
for word in wordList:
for i in range(L):
all_combo_dict[word[:i] + '*' + word[i+1:]].append(word)
queue = [(beginWord, 1)]
visited = [beginWord]
while queue:
current_word, level = queue.pop(0)
for i in range(L):
intermediates = current_word[:i] + '*' + current_word[i+1:]
for next_state in all_combo_dict[intermediates]:
if next_state == endWord:
return level + 1
if next_state not in visited:
queue.append((next_state, level + 1))
visited.append(next_state)
return 0
def diameterOfBinaryTree(self, root):
self.length = 1
def depth(root):
if not root: return 0
L = depth(root.left)
R = depth(root.right)
self.length = max(self.length, L + R + 1)
return max(L, R) + 1
depth(root)
return self.length - 1
def copyRandomList(self, head):
if not head: return None
# Insert a identity node without it's random pointer
tmp = head
while tmp:
newNode = RandomListNode(tmp.label, None, None)
newNode.next = tmp.next
tmp.next = newNode
tmp = tmp.next.next
tmp = head
# Move the random pointer to new Node
while tmp:
if tmp.random:
tmp.next.random = tmp.random.next
tmp = tmp.next.next
# Seperate old list from new list
newHead = head.next
pold = head
pnew = newHead
while pnew.next:
pold.next = pnew.next
pold = pold.next
pnew.next = pold.next
pnew = pnew.next
return newHead
def floodFill(self, image, sr, sc, newColor):
# DFS
color = image[sr][sc]
n_row = len(image)
n_col = len(image[0])
if image[sr][sc] == newColor: return image
def dfs(r, c):
if image[r][c] == color:
image[r][c] = newColor
if r > 0: dfs(r - 1, c) # Moving up
if r < n_row - 1: dfs(r + 1, c) # Moving down
if c > 0: dfs(r, c - 1) # Moving left
if c < n_col - 1: dfs(r, c + 1) # Moving right
dfs(sr, sc)
return image
def reverse(self, x):
INT_MAX = 2 ** 31 - 1
INT_MIN = -2 ** 31
isNegative = x < 0
if isNegative:
x = x * -1
rev = 0
while x != 0:
pop = x % 10
x = x // 10
if rev > INT_MAX // 10 or (rev == INT_MAX // 10 and pop > 7):
return 0
if -rev < INT_MIN // 10 or (-rev == INT_MIN // 10 and pop < -8):
return 0
rev = rev * 10 + pop
if isNegative:
return -rev
return rev
def myAtoi(self, sequence):
INT_MAX = 2 ** 31 - 1
INT_MIN = -2 ** 31
switch = False
isNegative = False
whiteList = [str(ele) for ele in range(10)]
answer = 0
whiteList.append('-')
whiteList.append('+')
for ele in sequence:
if ele == ' ' and switch:
break
if ele != ' ' and ele not in whiteList and not switch:
return 0
if ele != ' ' and ele not in whiteList and switch:
break
if ele != ' ' and ele in whiteList:
if not switch:
whiteList.pop() # Took out '+'
whiteList.pop() # Took out '-'
switch = True
if ele == '-':
isNegative = True
continue
if ele == '+':
continue
answer = answer * 10 + int(ele)
if isNegative:
if -answer < INT_MIN:
return INT_MIN
return -answer
if answer > INT_MAX:
return INT_MAX
return answer
def isPalindrome(self, x):
if x < 0:
return False
x = str(x)
def helper(x):
if not x:
return True
if x[0] != x[-1]:
return False
else:
return helper(x[1:-1])
return helper(x)
def intToRoman(self, num):
look_table = {1000: 'M',
500: 'D',
100: 'C',
50: 'L',
10: 'X',
5: 'V',
1: 'I',
}
self.answer = ''
def helper(num, base, divide_two, flag):
if base == 0:
return
if base == 1000:
for pop in range(num // base): self.answer = self.answer + look_table[base]
else:
if num // base == 4 and flag: # Handle 9***
self.answer = self.answer[:-1] + look_table[base] + look_table[base * 10]
elif num // base == 4 and (not flag): # Handle 4***
self.answer = self.answer + look_table[base] + look_table[base * 5]
else:
for _ in range(num // base):
self.answer = self.answer + look_table[base]
if num > base:
flag = True
else:
flag = False
if divide_two:
helper(num % base, base // 2, not divide_two, flag)
else:
helper(num % base, base // 5, not divide_two, flag)
helper(num, 1000, True, False)
return self.answer
def romanToInt(self, sequence):
look_table = {'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
"I": 1,
}
self.answer = 0
def helper(sequence):
if len(sequence) == 0:
return
if sequence[0] == 'C':
if len(sequence) > 1 and (sequence[1] == 'D' or sequence[1] == 'M'):
self.answer = self.answer + (look_table[sequence[1]] - look_table[sequence[0]])
helper(sequence[2:])
else:
self.answer = self.answer + look_table[sequence[0]]
helper(sequence[1:])
elif sequence[0] == 'X':
if len(sequence) > 1 and (sequence[1] == 'L' or sequence[1] == 'C'):
self.answer = self.answer + look_table[sequence[1]] - look_table[sequence[0]]
helper(sequence[2:])
else:
self.answer = self.answer + look_table[sequence[0]]
helper(sequence[1:])
elif sequence[0] == 'I':
if len(sequence) > 1 and (sequence[1] == 'V' or sequence[1] == 'X'):
self.answer = self.answer + look_table[sequence[1]] - look_table[sequence[0]]
print(self.answer)
helper(sequence[2:])
else:
self.answer = self.answer + look_table[sequence[0]]
helper(sequence[1:])
else:
self.answer = self.answer + look_table[sequence[0]]
helper(sequence[1:])
helper(sequence)
return self.answer
def longestCommonPrefix(self, list_sequence):
if len(list_sequence) == 0:
return ""
self.answer = list_sequence[0]
def compare(s1, s2):
idx = -1
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
break
idx = i
return s1[:idx + 1]
for i in range(1, len(list_sequence)):
self.answer = compare(self.answer, list_sequence[i])
return self.answer
def removeDuplicates(self, nums):
if len(nums) == 0: return 0
slow_run = 0
for fast_run in range(1, len(nums)):
if nums[fast_run] != nums[slow_run]:
slow_run += 1
nums[slow_run] = nums[fast_run]
nums = nums[:slow_run]
return nums[:slow_run]
def threeSum(self, nums):
nums.sort()
found = []
for index, num in enumerate(nums):
if num > 0:
break
if index > 0 and num == nums[index - 1]: continue
left = index + 1
right = len(nums) - 1
while left < right:
Sum = num + nums[left] + nums[right]
if Sum == 0 and not [num, nums[left], nums[right]] in found:
found.append([num, nums[left], nums[right]])
right = right - 1
elif Sum > 0:
right -= 1
else:
left += 1
return found
def fourSum(self, nums, target):
nums.sort()
found = []
for i in range(len(nums)):
if target < 0 and nums[i] > 0:
break
if target > 0 and nums[i] > target:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
res = target - nums[i]
for j in range(i + 1, len(nums)):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left = j + 1
right = len(nums) - 1
while left < right:
L = [nums[i], nums[j], nums[left], nums[right]]
if sum(L) == target and L not in found:
found.append(L)
right = right - 1
elif sum(L) < target:
left += 1
else:
right -= 1
return found
def threeSumClosest(self, nums, target):
nums.sort()
dic = {}
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
l = i + 1
r = len(nums) - 1
while l < r:
sum = nums[i] + nums[l] + nums[r]
if sum < target:
l += 1
dic[sum] = target - sum
elif sum > target:
r -= 1
dic[sum] = sum - target
else:
return target
return min(dic, key=dic.get)
def isValid(self, s):
look_table = {')': '(',
'}': '{',
']': '['
}
if not s or len(s) % 2 != 0:
return False
stack = []
for val in s:
if val in look_table:
if stack and stack.pop() != value:
return False
else:
stack.append(val)
return not stack
def generateParenthesis(self, n):
# using backtrack algorithm
self.answer = []
def helper(S = '', open = 0, close = 0):
if len(S) == 2 * n:
self.answer.append(S)
return
if open < n:
helper(S+'(', open + 1, close)
if close < open:
helper(S+')', open, close + 1)
helper()
return self.answer
def removeElement(self, nums, val):
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
def strStr(self, haystack, needle):
index = -1
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return index
def nextPermutation(self, nums):
# find the decreased number, find the element that "just larger" than
# the decreased number -> swap them -> reverse the order of the array
# after that index
if len(nums) < 2:
return
def get_next_larger_number_index(index, nums):
next_larger_number_index = len(nums)-1
for position in range(index+1, len(nums)):
if nums[position] <= nums[index]:
next_larger_number_index = position - 1
break
return next_larger_number_index
def reverse_num_list(start_index, nums):
start, end = start_index, len(nums)-1
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
previous_number = nums[-1]
for index in range(len(nums)-2, -1, -1):
if nums[index] < previous_number:
swap_index = get_next_larger_number_index(index, nums)
nums[index], nums[swap_index] = nums[swap_index], nums[index]
reverse_num_list(index+1, nums)
return
previous_number = nums[index]
reverse_num_list(0, nums)
def search(self, nums, target):
if len(nums) == 0:
return -1
if len(nums) == 1:
if nums[0] == target: return 0
else: return -1
def find_smallest_index(nums, low, high):
# [7, 8, 1, 2, 3, 4, 5, 6]
# [4, 5, 6, 7, 8, 1, 2, 3]
# [5, 6, 7, 8, 1, 2, 3, 4]
if nums[0] < nums[-1]: # Handle not rotated case
return 0
if low == high:
return low
mid = (low + high) // 2
# This section checks if mid + 1 or mid is minimum
if mid < high and nums[mid] > nums[mid + 1]:
return mid + 1
if mid > low and nums[mid] < nums[mid - 1]:
return mid
# This section determines if we should search the left part or right part
if nums[mid] > nums[low]: # Search right part
return find_smallest_index(nums, mid + 1, high)
return find_smallest_index(nums, low, mid) # Otherwise, search the left part
def binary_search(nums, left, right):
if len(nums) == 0:
return -1
if left >= right and nums[left] != target:
return -1
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] > target: # search left side
return binary_search(nums, left, mid)
if nums[mid] < target:
return binary_search(nums, mid + 1, right)
# [7, 8, 1, 2, 3, 4, 5, 6]
min_idx = find_smallest_index(nums, 0, len(nums) - 1)
if target == nums[min_idx]:
return min_idx
if target > nums[min_idx] and target <= nums[min_idx:][-1]: # search right side of the pivot
return binary_search(nums, min_idx + 1, len(nums) - 1)
return binary_search(nums, 0, min_idx)
def searchRange(self, nums, target):
if len(nums) == 0:
return [-1, -1]
self.answer = [-1, -1]
self.tmp = -1
# locate at least one target
def helper(nums, low, high):
if low == high: # Exit condition
if nums[low] != target: return
mid = (low + high) // 2
#print('low: ' + str(low))
#print('high: ' + str(high))
if nums[mid] == target:
self.tmp = mid
return
if nums[mid] > target:
helper(nums, low, mid)
else:
helper(nums, mid + 1, high)
# seach left side
def search_left(nums, high):
if high < 0:
self.answer[0] = 0
return
if nums[high] < target:
self.answer[0] = high + 1
return
if nums[high] >= target:
search_left(nums, high - 1)
def search_right(nums, low):
if low >= len(nums):
self.answer[-1] = len(nums) - 1
return
if nums[low] > target:
self.answer[-1] = low - 1
else:
search_right(nums, low + 1)
helper(nums, 0, len(nums) - 1)
print(self.tmp)
if self.tmp == -1: return self.answer
else:
self.answer[0], self.answer[1] = self.tmp, self.tmp
search_left(nums, self.tmp)
search_right(nums, self.tmp)
return self.answer
def searchInsert(self, nums, target):