forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode.py
executable file
·3418 lines (3113 loc) · 89 KB
/
leetcode.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
#!/usr/bin/env python
# 1.Single Number
# Fuck!!! use XOR
def single_number(num_list):
for num in num_list[1:]
if num is not None:
num_list[0] ^= num
return num_list[0]
# 2. Maximum depth of binary tree
def maximum_depth(root):
if root is None:
return 0
return max( maximum_depth(root.left), maximum_depth(root.right)) + 1
# 3. Same Tree
def is_same_tree(p, q):
# p q are both None so same
if p is None and q is None:
return True
# one of the node is None but the other is not, not same
if p is None or q is None:
return False
if p.data != q.data:
return False
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
# 4.Reverse Integer
def reverse(x):
if x < 0:
return (-1) * reverse( (-1) * x)
res = 0
while x > 0:
res = res*10 + x%10
x /= 10
return res
def reverse_int(num):
# Need to check negative, last digit zero
is_nagative = 1
if num < 0:
is_nagative = -1
digit_list = []
num = abs(num)
while num > 0:
digit_list.append(num%10)
num /= 10
result = 0
weight = len(digit_list)-1
for digit in digit_list:
result += digit * (10**weight)
weight -= 1
result *= is_nagative
return result
# 5. Unique Binary Search tree
def unique_bst(num):
if num <=1:
return num
return unique_bst_helper(1, num)
def unique_bst_helper(start, end):
if start >= end:
return 1
result = 0
for i in range(start, end+1):
# sum the result on the left ande on the right
result += unique_bst_helper(start, i-1) * unique_bst_helper(i+1, end)
return result
# 6. Best time to buy and sell
def stock_buy_sell(stock_list):
pre_price = stock_list[0]
buy_price = stock_list[0]
stock_empty = True
profit = 0
for i in range(1, len(stock_list)):
# price decreasing, sell at previous point
if stock_list[i] < pre_price:
if stock_empty:
# we got a lower buy price
buy_price = stock_list[i]
else:
profit += pre_price - buy_price
stock_empty = True
# stock increasing, stock empty false
else:
stack_empty = False
pre_price = stock_list[i]
# last sell
if not stock_empty:
profit += pre_price - buy_price
# 7. Linked List Cycle
def list_cycle(head):
slow = head
fast = head
while slow != fast:
slow = slow.next
fast = fast.next.next
fast = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast
# 8. BT Inorder traversal
# Iterative way
def inorder_traversal(root):
stack = []
res = []
current = root
while current is not None or len(stack)>0:
if current is not None:
stack.append(current)
current = current.left
elif len(stack)>0:
current = stack.pop()
res.append(current.val)
current = current.right
return res
def inorder_traversal(root):
if root is None:
return
inorder_traversal(root.left)
print root.data
inorder_traversal(root.right)
# 9. BT Preorder traversal
# Iterative way
def preorder_traversal(root):
stack = []
current = root
while current is not None or len(stack)>0:
if current is not None:
res.append(current.val)
stack.append(current)
current = current.left
elif len(stack)>0:
current = stack.pop()
current = current.right
return res
def preorder_traversal(root):
if root is None:
return
print root.data
preorder_traversal(root.left)
preorder_traversal(root.right)
# 10. Populate Next right poiters in each node
# This is a bit hard to think
def next_right_pointer(root):
if root is None:
return
if root.left is not None:
root.left.next = root.right
if root.right is not None and root.next is not None:
root.right.next = root.next.left
next_right_pointer(root.left)
next_right_pointer(root.right)
"""
Need to validate if this is correct
def next_right_pointer(root):
if root is None:
return
left = root.left
right = root.right
if left is not None and right is not None:
left.next = right
while left.right is not None:
left = left.right
right = right.left
left.next = right
next_right_pointer(root.left)
next_right_pointer(root.right)
"""
# Not using recursive, but also using extra space, so not a good result
def next_right_pointer(root):
if root is None:
return
prev = [root,]
while len(prev) > 0:
current = []
for i in range(1, len(prev)):
prev[i-1].next = prev
if node.left is not None:
current.append(node.left)
if node.right is not None:
current.append(node.right)
prev[-1].next = None
prev = current[:]
return root
# 11. Search Insert Position
# This is a O(n) method, need to think about something for O(log(n))
def searchInsert(A, target):
start = 0
end = len(A) - 1
while start <= end:
mid = (start + end) / 2
if A[mid] == target:
return mid
elif A[mid] < target: # need to search second half
start = mid + 1
else:
end = mid - 1
return start
# Too easy way, not the way wanted
def searchInsert_2(A, target):
for i, num in enumerate(A):
if target <= num:
return i
return len(A)
"""
Guess these two are not the best ways
def search_insert_position_1(num_list, num):
i = 0
while i <= len(num_list)-1:
if num <= num_list[i]:
return i
i += 1
return i
# No need to use recursive
def search_insert_position(num_list, num, start, end):
if start > end:
return start
mid = (start + end) / 2
if num_list[mid] == num:
return mid
elif num_list[mid] > num:
return search_insert_position(num_list, num, start, mid-1)
else:
return search_insert_position(num_list, num, mid+1, end)
"""
# 12. Remove Duplicates from Sorted List:
def deleteDuplicates(self, head):
if head is None or head.next is None:
return head
current = head
while current.next is not None:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return head
"""
No need to use prev
def remove_duplicates(head):
if head is None or head.next is None:
return head
prev = head
current = head.next
while current is not None:
if prev.data == current.data:
prev.next = current.next
else:
prev = current
currnet = current.next
return head
"""
# 13. Climbing Stairs
# Fuck you remember the num <= 2
# There's a way not to use recursive
def climb_stairs(num):
if num <= 2:
return num
return climb_stairs(num-1) + climb_stairs(num-2)
# 14. Maximum Subarray
# important is the way to think this shit!!!
def maximum_subarray(array):
sum = 0
max = MIN_INT
for i in range(0, len(array)):
sum += array[i]
if sum >= max:
max = sum
if sum < 0:
sum =0
return max
# dp way
# dp[i] = max(A[i], dp[i-1]+A[i])
# Note here it's A[i] not dp
# Because we don't need to store dp[i], so simplify to dp
def maxSubArray_2(self, A):
res = A[0]
dp = A[0]
for num in A[1:]:
dp = max(num, dp+num)
res = max(res, dp)
return res
# 15. Roman to Integer
def roman_2_integer(roman):
roman_map = { 'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
result = 0
for i in range(0, len(roman)):
if i > 0 and roman_map[roman[i]] > roman_map[roman[i-1]]:
result += roman_map[roman[i]] - 2 * roman_map[roman[i-1]]
else:
result += roman_map[roman[i]]
return result
# 16 Single Number II
# Check later
def single_number_2(num_list, num):
one = 0
two = 0
three = 0
for i in num_list:
two |= one & num_list[i];
one ^= num_list[i];
three = one & two;
one &= ~three;
two &= ~three;
return one
# 17 Remove Element
def remove_element(A, elem):
i = 0
for j, num in enumerate(A):
if num != elem:
A[i] = A[j]
i += 1
return i
# 18 Integer to Roman
# WOCAONIMA
def integer_2_roman(num):
digits = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD' ),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
result = ""
for digit in digits:
while num >= digit[0]:
result += digit[1]
num -= digit[0]
if num == 0:
break
return result
"""
def integer_2_roman(num):
digits = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD' ),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
result = ""
while len(digits) > 0:
(val, romn) = digits[0] # Unpacks the first pair in the list
if n < val:
digits.pop(0) # Removes first element
else:
n -= val
result += romn
return result
"""
# 19 Merge two sorted list
# Wo dou bu xiang xiang le
# Using dummy make life easier
def mergeTwoLists(l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 is not None and l2 is not None:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1 is not None:
cur.next = l1
if l2 is not None:
cur.next = l2
return dummy.next
"""
def merge_sorted_list(list1, list2):
head = None
prev = None
while list1 is not None and list2 is not None:
if head is None:
if list1.data < list2.data:
head = Node(list1.data)
list1 = list1.next
else:
head = Node(list2.data)
list2 = list2.next
prev = head
else:
if list2 is None or list1.data < list2.data:
new = Node(list1.data)
list1 = list1.next
else:
new = Node(list2.data)
list2 = list2.next
prev.next = new
prev = new
return head
"""
# 20. Balanced Binary Tree
# need to check if there's a better way
def balanced_bt(root):
if root is None:
return True
if abs(get_height(root.left) - get_height(root.right)) > 1:
return False
return balanced_bt(root.left) and balanced_bt(root.right)
def get_height(root):
if root is None:
return 0
else:
return max(get_height(root.left), get_height(root.right)) + 1
# 21. Convert sorted array to bst
def array_to_bst(num_list):
if num_list is None:
return None
return array_to_bst(num_list, 0, len(num_list)-1)
def array_to_bst_helper(num_list, start, end):
if start > end:
return
mid = (start + end) / 2
n = treeNode(num_list[mid])
n.left = array_to_bst_helper(num_list, start, mid - 1)
n.right = array_to_bst_helper(num_list, mid + 1, end)
return n
# 22. Remove Duplicates from sorted array
# Remember i+1, also don't forget length check
def removeDuplicates_2(A):
if len(A) <= 1:
return len(A)
i = 0
for j in range(1, len(A)):
if A[i] != A[j]:
A[i+1] = A[j]
i += 1
return i+1
"""
# Fuck remember it is length + 1 !!!!
def remove_duplicates_in_array(num_list):
length = 0
for i in range(1, len(num_list)):
if num_list[i] != num_list[length]:
length += 1
num_list[length] = num_list[i]
return length + 1
"""
# 23. Pascal's Triangle
# Fuck notice it's range(n-1) not n
def generate_1(numRows):
res = []
for j in range(numRows):
current = [1]
for i in range(1, j):
current.append(res[-1][i]+res[-1][i-1])
if j>=1:
current.append(1)
res.append(current[:])
return res
"""
def pascal_triangle_2(n):
if n == 1:
return [1]
prev = [1]
result = [prev, ]
for i in range(n-1):
prev_copy = prev[:]
prev_copy.append(0)
prev_copy.insert(0,0)
new_line = []
# first and last num always assume 0
for i in range(1, len(prev_copy)):
new_line.append(prev_copy[i] + prev_copy[i-1])
result.append(new_line)
prev = new_line
return result
# New way to think about this. Not appending 0 at beginning but append 1, and sum every other besides last one
# this is the fucking best way to do this
def pascal_triangle(n):
if n == 1:
return [1]
prev = [1]
result = [prev,]
for i in range(n-1):
new_line = []
# appen first 1
new_line.append(1)
for j in range(1, len(prev)):
new_line.append(prev[j] + prev[j-1])
# append last 1
new_line.append(1)
result.append(new_line)
prev = new_line
return result
"""
# 24. Merge sorted array
# code will be cleaner if pthon has --
def merge_sorted_array(l1, l2):
end = len(l1) + len(l2) - 1 # this will be the new end
end_1 = len(l1) - 1
end_2 = len(l2) - 1
while end_1 >= 0 and end_2 >= 0:
if l1[end_1] >= l2[end_2]:
l1[end] = l1[end_1]
end_1 -= 1
else:
l1[end] = l2[end_2]
end_2 -= 1
end -= 1
# if end_1 hit 0, then it's done. so only possibility is end_2 not hit zero
while end_2 >= 0:
l1[end] = l2[end_2]
end -= 1
end_2 -= 1
return l1
# 25. Swap Nodes in Pairs
def swap_nodes(head):
while head is not None and head.next is not None:
temp = head.data
head.data = head.next.data
head.next.data = temp
head = head.next.next
class Node:
def __init__(self, data):
self.data = data
self.next = None
def print_list(head):
while head is not None:
print head.data
head = head.next
# 26. Symmetric Tree
def symmetric_tree(root):
if root is None:
return True
return is_symetric(root.left, root.right)
def is_symmetric(p, q):
if p is None and q is None:
return True
elif p is None or q is None or p.data != q.data:
return False
else:
return is_symmetric(p.left, q.right) and is_symmetric(p.right, q.left)
# Iterative way
def isSymmetric_2(root):
if root is None:
return True
queue = collections.deque()
queue.append(root.left)
queue.append(root.right)
while len(queue)>0:
t1 = queue.popleft()
t2 = queue.popleft()
if t1 is None and t2 is None:
continue
if t1 is None or t2 is None or t1.val != t2.val:
return False
queue.append(t1.left)
queue.append(t2.right)
queue.append(t1.right)
queue.append(t2.left)
return True
# 27. Gray Code
def grayCode(n):
i = 0
ret = []
while i < 2**n:
ret.append(i>>1^i)
i += 1
return i
# This is better than below one which is easier to remember,
# But this question, we want int instead of string binary
def grayCodeGen(n):
if n == 1:
return ['0', '1']
else:
ret = []
code_list = grayCodeGen_2(n-1)
for code in code_list:
ret.append('0' + code)
for code in code_list[::-1]:
ret.append('1' + code)
return ret
# A easy understandable way to solve this
def graycode(numbits, reverse = False):
if numbits == 1:
if reverse:
yield "1"
yield "0"
else:
yield "0"
yield "1"
else:
if reverse:
# all the "1"s start first
gcprev = graycode(numbits - 1, False)
for code in gcprev:
yield "1" + code
gcprev = graycode(numbits - 1, True)
for code in gcprev:
yield "0" + code
else:
# all the "0" start first
gcprev = graycode(numbits - 1, False)
for code in gcprev:
yield "0" + code
gcprev = graycode(numbits - 1, True)
for code in gcprev:
yield "1" + code
# 84. N-Queens
def n_queens(n):
pass
def is_valid(result, r):
for i in range(r):
if result[i] == result[r] or abs((result[i]-result[r]) - (i-r)) == 0:
return False
return True
# 28. N-Queens II
def n_queens_ii():
pass
# 29. Sort Colors
# Passing only once
def sort_colors(A):
index = 0
red_index = 0
blue_index = len(A) - 1
while index <= blue_index:
if A[index] == 0: # red
swap(A, index, red_index)
index += 1
red_index += 1
elif A[index] == 2: # blue
swap(A, index, blue_index)
index += 1 # Remember this index won't increase
blue_index -= 1
else:
index += 1
return A
# Passing twice
def sort_colors(list):
counter = [0] * 3
for i in list:
if i == 0:
counter[0] += 1
elif i == 1:
counter[1] += 1
else:
counter[2] += 1
result = [0] * counter[0] + [1] * counter[1] + [2] * counter[2]
return result
# 30. Binary Tree Level Order Traversal II
# Note: this returns a stack, in order to return a reverse one, still need to reverse them
def bt_level_traversal_ii(root):
if root is None:
return
# Use pop() to pop the result later
stack = [[root,],]
prev = [root,]
current = []
while len(prev) > 0:
for node in prev:
if node.left is not None:
current.append(node.left)
if node.right is not None:
current.append(node.right)
if len(current) > 0:
stack.append(current)
prev = current
current = []
return stack
# 31. Permutations
# Need to fucking remember this. Divide and Conquer
def permute(num):
if not num:
return [[]]
else:
res = []
for i, e in enumerate(num):
rest = num[:i] + num[i + 1:]
rest_perms = permute(rest)
for perm in rest_perms:
res.append( perm + [e,])
return res
# 32. Generate Parentheses
# With simpler implementation
def generateParenthesis(n):
ret = []
generateParenthesis_helper(n, n, '', ret)
return ret
def generateParenthesis_helper(left, right, res, ret):
if left == 0 and right ==0:
ret.append(res[:])
return
if left > 0:
generateParenthesis_helper(left-1, right, res+'(', ret)
if right > left:
generateParenthesis_helper(left, right-1, res+')', ret)
"""
def parentheses_gen(n):
res = []
cand = ''
gp(n, n, cand, res)
return res
def gp(left, right, cand, res):
if left > right or left < 0:
return
elif left == 0 and right == 0:
res.append(cand)
else:
gp(left - 1, right, cand + '(', res)
gp(left, right - 1, cand + ')', res)
"""
# 33. Best time to buy and sell II
# Remember to pre check
def stock_buy_sell_I(prices):
if len(prices) < 1:
return 0
min_price = prices[0]
max_profit = prices[0]
for price in prices:
max_profit = max(max_profit, price - min_price)
min_pirce = min(min_price, price)
return max_profit
def stock_buy_sell_II(prices):
profit = 0
prev = price[0]
for price in prices[1:]:
if price >= prev: # Increasing
profit += price - prev
prev = price
return profit
"""
Wrong solution
def stock_buy_sell_III(prices):
profit_2 = [0] * 2
prev = price[0]
low_price = price[0]
for price in prices[1:]:
if price < prev: # Reached high point/decreasing, calculate profit, got new low_price
profit = low_price - prev
if prev != low_price: # Means this is the high point
profit_2 = calculate_max_2(profit, profit_2)
low_price = price
prev = price
# Need to calcualte the last one
profit_2 = calculate_max_2(prev - low_price, profit_2)
return profit_2
"""
# A little bit Dynamic Programming
# 1. in-order pass: use profit = price - min_price
# 2. back-order pass: use profit = max_price - price
def stock_buy_sell_III(prices):
n = len(prices)
m1 = [0] * n
m2 = [0] * n
max_profit1 = 0
min_price1 = prices[0]
max_profit2 = 0
max_price2 = prices[-1]
# It's O(3n) which is O(n)
for i in range(n):
max_profit1 = max(max_profit1, prices[i] - min_price1)
m1[i] = max_profit1
min_price1 = min(min_price1, prices[i])
for i in range(n):
max_profit2 = max(max_profit2, max_price2 - prices[n - 1 - i])
m2[n - 1 - i] = max_profit2
max_price2 = max(max_price2, prices[n - 1 - i])
max_profit = 0
for i in range(n):
max_profit = max(m1[i] + m2[i], max_profit)
return max_profit
# 34. Plus One
# Fuck you cheat guys
def plusOne(digits):
i = len(digits) - 1
carry = 1
while i >= 0 and carry == 1: # So many detail! No need to continue calculation if carry == 0
s = digits[i] + carry # Calculate s first
digits[i] = s % 10
carry = s / 10
i -= 1
if carry == 1: # Last check
digits.insert(0, 1)
return digits
# 35. Roatate Image
def rotate_image(matrix):
rotated = []
for j in range(len(matrix[0])):
new_row = []
for i in range(len(matrix)-1, -1, -1): # from n-1 to 0
new_row.append(matrix[i][j])
rotated.append(new_row)
return rotated
# Fuck remember this is different from the 150Ti
def link_list_cycle(head):
slow_runner = head
fast_runner = head
while fast_runner is not None and fast_runner.next is not None:
fast_runner = fast_runner.next
slow_runner = slow_runner.next
if fast_runner == slow_runner:
return True
return False
# 36. Linked List Cycle II
# Remember to set slow = head.next and fast = head.next.next before entering the loop
def link_list_cycle_II():
if head is None or head.next is None:
return None
slow = head.next
fast = head.next.next
while slow!=fast:
if fast is None or fast.next is None:
return None
slow = slow.next
fast = fast.next.next
fast = head
while slow!=fast:
slow = slow.next
fast = fast.next
return slow
# 37. Unique Path
def unique_path(m,n):
if (m, n) == (0,0):
return 0
elif (m, n) in [(1,0), (0,1)]:
return 1
elif m == 0:
return unique_path(m, n-1)
elif n == 0:
return unique_path(m-1,n)
else:
return unique_path(m-1,n) + unique_path(m, n-1)
def unique_path_ii(map, m, n):
if (m, n) == (0,0):
return 0
elif (m,n) in [(1,0),(0,1)]:
return 1
else:
if not valid_point(map, m-1, n) and not valid_point(map, m, n-1): # No where to go
return 0
elif valid_point(map, m-1, n) and valid_point(map, m, n-1): # Can go both directions
return unique_path_ii(map, m-1, n) + unique_path_ii(map, m, n-1)
else: # Can only go one direction
if valid_point(map, m-1, n):
return uniqe_path_ii(map, m-1, n)
else:
return unique_path_ii(map, m, n-1)
def valid_point(map, m, n):
if m < 0 or n < 0:
return False
if map[m][n] == 1:
return False
return True
# This solution may look a bit stupid
# 38. Binary Tree Postorder Traversal
# Doing in iterative way
def bt_post_traversal(root):
stack = [root]
output = []
while len(stack)>0:
node = stack.pop()
output.append(node.val)
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
return output[::-1]
# Doing recursive is trivial
def bt_post_traversal(root):
if root is None:
return
bt_post_traversal(root.left)
bt_post_traversal(root.right)
print root.data
# Any pre/in/post-order tree traversal are all dfs which use stack
# 39. Binary Tree Level Order Traversal
def levelOrder(root):
res = []
if root is None:
return res
queue = []
level = []
queue.append(root)
queue.append(None)
while len(queue)>0:
node = queue.pop(0)
if node is None:
res.append(level[:])
level = []
if len(queue)>0:
queue.append(None)
else:
level.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return res
"""
The problem here is we want a result in int, but not copy the node
def bt_level_order_traversal(root):
if root is None:
return []
result = [[root]]
current = []
prev = [root,]
while len(prev):
for node in prev:
if node.left is not None:
current.append(node.left)
if node.right is not None:
current.append(node.right)
if len(current) > 0:
result.append(current)
prev = current