-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathctci.py
More file actions
1479 lines (1306 loc) · 42.5 KB
/
Copy pathctci.py
File metadata and controls
1479 lines (1306 loc) · 42.5 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
# coding: utf-8
from collections import defaultdict, Counter
from pprint import pprint
# TODO: hanoi, 5.2, 5.7, 7.x, 19.9
# known bugs: 19.6 doesnt do "and"
def oneone(s):
'Implement an algorithm to determine if a string has all unique characters.'
chars = set()
for c in s:
if c in chars:
return False
chars.add(c)
return True
def oneone2(s):
'What if you can not use additional data structures?'
if not s:
return True
le = len(s)
for i in range(le-1):
for j in range(i+1, le):
if i != j and s[i] == s[j]:
return False
return True
def onetwo(s):
'''Write code to reverse a C-Style String.
(C-String means that “abcd” is represented as five characters, including the null character.)'''
# lets pretend Python has mutable strings
s = list(s)
max_idx = len(s) - 1
for i in range(len(s)/2):
t = s[i]
s[i] = s[max_idx - i]
s[max_idx - i] = t
return ''.join(s)
def onethree(s):
'''
Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not.
'''
# note this doesnt do unicode or any other fanciness
s = list(s)
# pretend bit vector
bitvector = [False] * 128
cur_idx = 0
for c in s:
pos = ord(c)
if not bitvector[pos]:
bitvector[pos] = True
s[cur_idx] = c
cur_idx += 1
return ''.join(s[:cur_idx])
def onefour(s, t):
'Write a method to decide if two strings are anagrams or not.'
# We could of course do
# sorted(s) == sorted(t)
# Counter(s) == Counter(t)
# this is more in the spirit of the book
d = {}
for c in s:
if not c in d:
d[c] = 0
d[c] += 1
for c in t:
if not c in d or not d[c]:
return False
d[c] -= 1
return not any(d.values())
def onefive(s):
'Write a method to replace all spaces in a string with ‘%20’.'
# this is stupid
return s.replace(' ', '%20')
def onesix(matrix):
'''
Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
'''
# go in layers and do a 4-way swap on pixels
if not matrix:
return matrix
n = len(matrix[0])
for layer in range(n/2):
first = layer
last = n - 1 - layer
for i in range(first, last):
offset = i - layer
# top = matrix[layer][i]
# left = matrix[last-offset][layer]
# right = matrix[i][last]
# bottom = matrix[last][last-offset]
# temp = top
temp = matrix[layer][i]
# top = left
matrix[layer][i] = matrix[last-offset][layer]
# left = bottom
matrix[last-offset][layer] = matrix[last][last-offset]
# bottom = right
matrix[last][last-offset] = matrix[i][last]
# right = temp
matrix[i][last] = temp
return matrix
def oneseven(matrix):
'''Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column is set to 0.'''
if not matrix:
return matrix
N = len(matrix)
M = len(matrix[0])
null_hori = set()
null_vert = set()
for i in range(N):
for j in range(M):
if matrix[i][j] == 0:
null_hori.add(i)
null_vert.add(j)
for i in range(N):
for j in range(M):
if i in null_hori or j in null_vert:
matrix[i][j] = 0
return matrix
def oneeight(s1, s2):
'''
Assume you have a method isSubstring which checks if one word is a substring of
another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using
only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
'''
return s1 in s2+s2
def twoone(node):
'''
Write code to remove duplicates from an unsorted linked list.
'''
seen = set()
prev = None
while node is not None:
if node.value in seen:
prev.next = node.next
else:
seen.add(node.value)
prev = node
node = node.next
def twoone2(node):
'''FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?'''
while node is not None:
val = node.value
run_prev = node
run_ahead = node.next
while run_ahead is not None:
if run_ahead.value == val:
run_prev.next = run_ahead.next
run_prev = run_ahead
run_ahead = run_ahead.next
node = node.next
def twotwo(node, n):
'''Implement an algorithm to find the nth to last element of a singly linked list.'''
run_ahead = node
for _ in range(n):
if run_ahead is None:
raise ValueError('Linked list is shorter than n')
run_ahead = run_ahead.next
while run_ahead is not None:
node = node.next
run_ahead = run_ahead.next
return node
def twothree(node):
'''
Implement an algorithm to delete a node in the middle of a single linked list, given
only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e
'''
if node.next is None:
raise ValueError('need at least one element following to delete this node')
prev = node
node = node.next
while node is not None:
prev.value = node.value
prev = node
node = node.next
prev.next = None
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return 'Node(%s, %s)' % (self.value if self.value is not None else '', self.next)
def twofour(node1, node2):
'''
You have two numbers represented by a linked list, where each node contains a sin-
gle digit. The digits are stored in reverse order, such that the 1’s digit is at the head of
the list. Write a function that adds the two numbers and returns the sum as a linked
list.
EXAMPLE
Input: (3 -> 1 -> 5) + (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
'''
carry = 0
start = None
while True:
v1 = v2 = 0
if node1 is not None:
v1 = node1.value
if node2 is not None:
v2 = node2.value
new_value = v1+v2+carry
if not new_value:
break
carry, digit = divmod(new_value, 10)
new = Node(digit)
if start is None:
start = current_new = new
else:
current_new.next = new
current_new = new
if node1 is not None:
node1 = node1.next
if node2 is not None:
node2 = node2.next
current_new.next = None
return start
# n1 = Node(value=3, next=Node(value=1, next=Node(value=5)))
# n2 = Node(value=5, next=Node(value=9, next=Node(value=2)))
# print twofour(n1, n2)
def twofive(node):
'''Given a circular linked list, implement an algorithm which returns node at the begin-
ning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an
earlier node, so as to make a loop in the linked list.
EXAMPLE
input: A -> B -> C -> D -> E -> C [the same C as earlier]
output: C
'''
seen = set()
while node is not None:
if node in seen:
return node
seen.add(node)
node = node.next
return False
def threeone():
'''Describe how you could use a single array to implement three stacks.'''
# Give each stack a third of the array.
# Alternative idea: If speed doesnt matter, grow one from the front,
# one from the end, one from the middle, alternating between left and right :)
def threetwo():
'''
How would you design a stack which, in addition to push and pop, also has a function
min which returns the minimum element? Push, pop and min should all operate in
O(1) time.
'''
# for every element keep track of the min of all the elements beneath it
class Stack(object):
def __init__(self, values=None):
self.stack = []
self.mins = []
if values is not None:
for v in values:
self.push(v)
def push(self, value):
try:
cur_min = self.min()
except IndexError:
cur_min = float('inf')
self.mins.append(min(cur_min, value))
return self.stack.append(value)
def pop(self):
self.mins.pop()
return self.stack.pop()
def peek(self):
return self.stack[-1]
def min(self):
return self.mins[-1]
def __repr__(self):
return repr(self.stack)
return Stack
def threethree():
'''
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. There-
fore, in real life, we would likely start a new stack when the previous stack exceeds
some threshold. Implement a data structure SetOfStacks that mimics this. SetOf-
Stacks should be composed of several stacks, and should create a new stack once
the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should
behave identically to a single stack (that is, pop() should return the same values as it
would if there were just a single stack).
'''
class SetOfStacks(object):
def __init__(self, values=None, maxlen=10):
self.maxlen = maxlen
self.stacks = [[]]
if values is not None:
for v in values:
self.push(v)
def push(self, value):
if len(self.stacks[-1]) >= self.maxlen:
self.stacks.append([])
self.stacks[-1].append(value)
def pop(self):
if len(self.stacks) == 1 and not self.stacks[0]:
raise IndexError('pop from empty stack')
if not self.stacks[-1]:
self.stacks.pop()
return self.stacks[-1].pop()
def peek(self):
if not self.stacks[-1]:
return self.stacks[-2][-1]
return self.stacks[-1][-1]
def threethree2():
'''
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific
sub-stack.
'''
class SetOfStacks(object):
def __init__(self, values=None, maxlen=10):
self.maxlen = maxlen
self.stacks = [[]]
if values is not None:
for v in values:
self.push(v)
def push(self, value):
for stack in self.stacks:
if len(stack) != self.maxlen:
stack.append(value)
return
self.stacks.append([value])
def pop(self):
if len(self.stacks) == 1 and not self.stacks[0]:
raise IndexError('pop from empty stack')
if not self.stacks[-1]:
self.stacks.pop()
return self.stacks[-1].pop()
def popAt(self, stack_num):
return self.stacks[stack_num].pop()
def peek(self):
if not self.stacks[-1]:
return self.stacks[-2][-1]
return self.stacks[-1][-1]
def threefour(A, B=None, C=None):
'''In the classic problem of the Towers of Hanoi, you have 3 rods and N disks of different
sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending
order of size from top to bottom (e.g., each disk sits on top of an even larger one). You
have the following constraints:
(A) Only one disk can be moved at a time.
(B) A disk is slid off the top of one rod onto the next rod.
(C) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first rod to the last using Stacks.
'''
pass
def threefive():
class MyQueue(object):
def __init__(self, values=None):
self.stack = []
self.other = []
if values is not None:
for v in values:
self.put(v)
def put(self, value):
self.stack.append(value)
def get(self):
while self.stack:
self.other.append(self.stack.pop())
elem = self.other.pop()
while self.other:
self.stack.append(self.other.pop())
return elem
def __repr__(self):
return repr(self.stacks[self.state])
return MyQueue
def threesix(stack):
'''
Write a program to sort a stack in ascending order. You should not make any assump-
tions about how the stack is implemented. The following are the only functions that
should be used to write this program: push | pop | peek | isEmpty.
'''
Stack = threetwo()
other = Stack()
other.push(stack.pop())
while not stack.isEmpty():
elem = stack.pop()
moved = 0
while other.peek() > elem:
stack.push(other.pop())
moved += 1
other.push(elem)
for _ in range(moved):
other.push(stack.pop())
return other
# Stack = threetwo()
# class SS(Stack):
# def isEmpty(self):
# return not self.stack
# s = SS([5,3,2])
# print threesix(s)
def fourone(root):
'''
Implement a function to check if a tree is balanced. For the purposes of this question,
a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
from the root by more than one.
'''
fourone.minh, fourone.maxh = float('-inf'), float('inf')
def walk(node, depth=0):
if node is None:
return
if not node.left and not node.right:
fourone.minh = max(depth, fourone.minh)
fourone.maxh = min(depth, fourone.maxh)
walk(node.left, depth+1)
walk(node.right, depth+1)
walk(root)
return abs(fourone.maxh - fourone.minh) <= 1
# from node import Node, tree
# print fourone(tree)
def fourtwo(n1, n2):
'''Given a directed graph, design an algorithm to find out whether there is a route be-
tween two nodes.
'''
seen = set()
stack = [n1]
while stack:
node = stack.pop()
if node in seen:
seen.add(node)
else:
continue
for c in node.children:
if c is n2:
return True
stack.append(c)
return False
def fourthree(arr):
'''
Given a sorted (increasing order) array, write an algorithm to create a binary tree with
minimal height.
'''
class Tree:pass
tree = Tree()
def insert(arr):
if not arr:
return
middle = len(arr)/2
tree.insert(arr[middle])
insert(arr[:middle])
insert(arr[middle+1:])
insert(arr)
return tree
def fourfour(tree):
'''
Given a binary search tree, design an algorithm which creates a linked list of all the
nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).
'''
levels = defaultdict(list)
def walk(node, depth):
if node is None:
return
levels[depth].append(node)
walk(node.left, depth+1)
walk(node.right, depth+1)
walk(tree, 0)
return levels
def fourfive(node):
'''
Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in
a binary search tree where each node has a link to its parent.
'''
'''
5
/ \
4 10
/ / \
1 8 12
/ / \ / \
0 6 9 11 13
'''
if node.right:
walk = node.right
while walk.left:
walk = walk.left
return walk
if node.parent.left is node:
return node.parent
if node.parent.right is node:
node = node.parent
while True:
if node is None:
# we got the last node
return False
if node.parent.left is node:
return node.parent
node = node.parent
return False
def foursix(tree, n1, n2):
'''Design an algorithm and write code to find the first common ancestor of two nodes
in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not
necessarily a binary search tree.
'''
def depth(root, node):
depth.found = -1
def walk(root, dep):
if root is None:
return
if depth.found != -1:
return
if root is node:
depth.found = dep
walk(root.left, dep+1)
walk(root.right, dep+1)
walk(root, 0)
return depth.found
d1 = depth(tree, n1)
d2 = depth(tree, n2)
lower, higher = n1, n2
if d1 < d2:
lower, higher = higher, lower
print d1, d2
for _ in range(abs(d2-d1)):
higher = higher.parent
while n1 is not None:
if n1 is n2:
return n1
n1 = n1.parent
n2 = n2.parent
return False
def fourseven(t1, t2):
'''
You have two very large binary trees: T1, with millions of nodes, and T2, with hun-
dreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
'''
def inorder_stringify(tree):
node_strings = []
def walk(node):
if node is None:
return
walk(node.left)
node_strings.append(str(node.value))
walk(node.right)
walk(tree)
return ','.join(node_strings)
s1 = inorder_stringify(t1)
s2 = inorder_stringify(t2)
return s2 in s1
def foureight(tree):
'''You are given a binary tree in which each node contains a value. Design an algorithm
to print all paths which sum up to that value. Note that it can be any path in the tree
- it does not have to start at the root.
'''
zero_paths = []
def walk(node, sofar=0):
if node is None:
return
p = node.parent
path = []
sofar_up = node.value
while p:
sofar_up -= p.value
path.append(p)
if sofar_up == 0:
zero_paths.append(path[::-1])
p = p.parent
walk(node.left, sofar+node.value)
walk(node.right, sofar+node.value)
return zero_paths
def fiveone(N, M, i, j):
'''
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a
method to set all bits between i and j in N equal to M (e.g., M becomes a substring of
N located at i and starting at j).
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
'''
# all 1s
ones = 2 ** 31 + 1
left = ones - (1 << (j - 1))
right = 1 << (i - 1)
mask = left | right
return (N & mask) | (M << i)
def fivetwo():
'''Given a (decimal - e.g. 3.72) number that is passed in as a string, print the binary rep-
resentation. If the number can not be represented accurately in binary, print “ERROR”
'''
def fivethree(i):
'''
Given an integer, print the next smallest and next largest number that have the same
number of 1 bits in their binary representation.
'''
s = bin(i)[2:]
all_ones = all(c == '1' for c in s)
if all_ones:
return False, '10' + s[1:]
big = s.rfind('01')
if big == -1:
bigger = s + '0'
else:
bigger = s[:big] + '10' + sorted(s[big+2:], reverse=True)
small = s.rfind('10')
if small == -1:
smaller = False
else:
smaller = s[:small] + '01' + sorted(s[small+2:])
return smaller.lstrip('0'), bigger
def fivefour():
'''Explain what the following code does: ((n & (n-1)) == 0).'''
# base 2
def fivefive(a, b):
'''
Write a function to determine the number of bits required to convert integer A to
integer B.
Input: 31, 14
Output: 2
'''
# Levenshtein is cooler
# from Levenshtein import distance
# return distance(bin(a)[2:], bin(b)[2:])
xor = a ^ b
return sum(bool(xor & (1 << i)) for i in range(32))
def fivesix(a):
'''
Write a program to swap odd and even bits in an integer with as few instructions as
possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc)
'''
to_the_left = (int('01' * 16, 2) & a) << 1
to_the_right = (int('10' * 16, 2) & a) >> 1
return to_the_left | to_the_right
def fiveseven():
'''
An array A[1...n] contains all the integers from 0 to n except for one number which is
missing. In this problem, we cannot access an entire integer in A with a single opera-
tion. The elements of A are represented in binary, and the only operation we can use
to access them is “fetch the jth bit of A[i]”, which takes constant time. Write code to
find the missing integer. Can you do it in O(n) time?
'''
# meh
def eightone(n):
'''Write a method to generate the nth Fibonacci number.'''
if not n:
return 0
a = b = 1
for _ in range(n-2):
c = a + b
a = b
b = c
return b
def eighttwo(N, offlimits=None):
'''
Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can
only move in two directions: right and down. How many possible paths are there for
the robot?
FOLLOW UP
Imagine certain squares are “off limits”, such that the robot can not step on them.
Design an algorithm to get all possible paths for the robot.
'''
paths = []
def walk(x, y, path=None):
if x >= N or y >= N:
return
if (x,y) in offlimits:
return
if path is None:
path = []
path = path[:]
path.append((x,y))
if x == N - 1 and y == N -1:
paths.append(path)
walk(x+1, y, path)
walk(x, y+1, path)
if offlimits is None:
offlimits = []
offlimits = set(offlimits)
walk(0, 0)
return paths
def eightthree(s):
'''
Write a method that returns all subsets of a set.
'''
if len(s) <= 1:
return [s]
subs = []
for i in range(len(s)):
li = s[:]
li.pop(i)
subs.append(li)
subs.extend(eightthree(li))
return set(map(tuple, subs))
def eightfour(s):
'''Write a method to compute all permutations of a string.'''
if len(s) <= 1:
return [s]
if len(s) == 2:
return [s, s[::-1]]
permuts = eightfour(s[:-1])
result = []
for p in permuts:
for i in range(len(p)+1):
result.append(p[:i] + s[-1] + p[i:])
return result
def eightfive(N):
'''
Implement an algorithm to print all valid (e.g., properly opened and closed) combi-
nations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
'''
def walk(s, l, r):
if l > 0:
walk(s + '(', l-1, r)
if r > l:
walk(s + ')', l, r-1)
if not l and not r:
print s
walk('', N, N)
def eightsix(screen, point, color):
'''
Implement the “paint fill” function that one might see on many image editing pro-
grams. That is, given a screen (represented by a 2 dimensional array of Colors), a
point, and a new color, fill in the surrounding area until you hit a border of that col-
or.’
'''
max_x = len(screen[0])
max_y = len(screen)
seen = set()
x, y = point
orig_color = screen[y][x]
def walk(x,y):
if x < 0 or y < 0 or x >= max_x or y >= max_y:
return
if (x,y) in seen:
return
else:
seen.add((x,y))
if screen[y][x] != orig_color:
return
screen[y][x] = color
walk(x+1,y)
walk(x,y+1)
walk(x-1,y)
walk(x,y-1)
walk(x,y)
def eightseven(n):
'''
Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and
pennies (1 cent), write code to calculate the number of ways of representing n cents.
'''
quantities = 25, 10, 5, 1
all_ways = set()
def walk(current):
if sum(current) == n:
all_ways.add(tuple(sorted(current)))
return
for q in reversed(quantities):
if sum(current) + q > n:
break
walk(current[:] + [q])
walk([])
return all_ways
def eighteight(N=8):
'''
Write an algorithm to print all ways of arranging eight queens on a chess board so
that none of them share the same row, column or diagonal.
'''
def xitout(board, x, y):
def exo(board, x, y):
if x >= 0 and y >= 0 and x < N and y < N:
board[y][x] = 'X'
for i in range(N):
board[y][i] = 'X'
board[i][x] = 'X'
for i in range(1, N):
# diagonal
exo(board, x+i, y+i)
exo(board, x+i, y-i)
exo(board, x-i, y+i)
exo(board, x-i, y-i)
initial_board = [[' ' for _ in range(N)] for _ in range(N)]
all_arrangements = []
def walk(board):
queens = [(x,y) for y in range(N) for x in range(N) if board[y][x] == 'Q']
if len(queens) == N:
all_arrangements.append(queens)
for y in range(N):
for x in range(N):
if board[y][x] != ' ':
continue
# make a new board
new = [row[:] for row in board]
# X it out
xitout(new, x, y)
# place a queen
new[y][x] = 'Q'
walk(new)
walk(initial_board)
return set(map(tuple, all_arrangements))
def nineone(A, B, last_valid_a):
'''
You are given two sorted arrays, A and B, and A has a large enough buffer at the end
to hold B. Write a method to merge B into A in sorted order.
'''
idx = len(A) - 1
a_idx = last_valid_a
b_idx = len(B) - 1
while a_idx >= 0 and b_idx >= 0:
a, b = A[a_idx], B[b_idx]
if a > b:
A[idx] = a
a_idx -= 1
else:
A[idx] = b
b_idx -= 1
idx -= 1
while b_idx >= 0:
A[idx] = B[b_idx]
b_idx -= 1
idx -= 1
return A
def ninetwo(arr):
'''
Write a method to sort an array of strings so that all the anagrams are next to each
other.
'''
return sorted(arr, cmp=lambda a,b: cmp(sorted(a), sorted(b)))
def ninethree(arr, value):
'''
Given a sorted array of n integers that has been rotated an unknown number of
times, give an O(log n) algorithm that finds an element in the array. You may assume
that the array was originally sorted in increasing order.
EXAMPLE:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 8 (the index of 5 in the array)
'''
l = 0
r = len(arr) - 1
while l <= r:
middle = (l + r) / 2
if arr[middle] == value:
return middle
if arr[l] <= arr[middle]:
if value > arr[middle]:
l = middle + 1
elif value >= arr[l]:
r = middle - 1
else:
l = middle + 1
elif value < arr[middle]:
r = middle -1
elif value <= arr[r]:
l = middle + 1
else:
r = middle - 1
return -1
# print ninethree(map(int, '15 16 19 20 25 1 3 4 5 7 10 14'.split()), 5)
def ninefour():
'''
If you have a 2 GB file with one string per line, which sorting algorithm would you use
to sort the file and why?
'''
# external sort
def ninefive(arr, value):
'''
Given a sorted array of strings which is interspersed with empty strings, write a meth-
od to find the location of a given string.
Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4
Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1
'''
l = 0
r = len(arr) - 1
while l <= r:
middle = cur = (l + r) / 2
while arr[cur] == '':
if cur <= 0:
cur = middle + 1
while arr[cur] == '':
if cur >= len(arr):
break
cur += 1
break
cur -= 1
if arr[cur] == value:
return cur
if arr[cur] <= value:
r = middle - 1
else:
l = middle + 1
return -1
def ninesix(arr, value):
'''