-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblems.py
More file actions
1892 lines (1653 loc) · 72.8 KB
/
Copy pathproblems.py
File metadata and controls
1892 lines (1653 loc) · 72.8 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
"""Interview problem bank: Codility-style tasks + the LeetCode patterns that
keep showing up in real screens.
Each problem stores its reference solution as SOURCE. The source is exec'd once
at import to produce the function that computes the expected answers, so the
"Show solution" button always shows code that provably passes the tests.
Every problem also gets fresh RANDOM test cases each time you open it, on top of
its fixed examples - so re-doing a problem is never just replaying a memorised
answer.
"""
from __future__ import annotations
import random
from dataclasses import dataclass, field
from typing import Callable
import i18n
import problems_de
from tasks import Task, make_cases, starter_for
BANK: list["Problem"] = []
@dataclass
class Problem:
id: str
title: str
difficulty: str
topic: str
func: str
params: str
statement: str
solution: str
complexity: str = ""
hints: list[str] = field(default_factory=list)
fixed: list = field(default_factory=list)
rand: Callable[[random.Random], tuple] | None = None
n_random: int = 4
notes: str = ""
starter: str = ""
checker_src: str = "" # optional check(args, got) when several answers are valid
ref: Callable = None # filled in by P()
@property
def display_title(self) -> str:
de = problems_de.PROBLEMS_DE.get(self.id, {})
return de.get("title", self.title) if i18n.is_de() else self.title
def build(self, rng: random.Random | None = None) -> Task:
rng = rng or random.Random()
samples = list(self.fixed)
if self.rand:
for _ in range(self.n_random):
try:
samples.append(self.rand(rng))
except Exception: # a generator hiccup must never kill the UI
break
task = Task(
id=self.id, title=self.title, func=self.func,
statement=self.statement.strip(),
starter=self.starter or starter_for(self.func, self.params),
cases=make_cases(self.ref, samples, hidden_from=min(3, len(self.fixed))),
hints=self.hints, solution=self.solution.strip(),
difficulty=self.difficulty, topic=self.topic,
complexity=self.complexity, source="interview", notes=self.notes,
checker_src=self.checker_src,
)
return i18n.localize_task(task, problems_de.PROBLEMS_DE.get(self.id))
def P(pid, title, difficulty, topic, func, params, statement, solution,
complexity="", hints=(), fixed=(), rand=None, n_random=4, notes="",
starter="") -> Problem:
ns: dict = {}
exec(solution, ns)
prob = Problem(id=pid, title=title, difficulty=difficulty, topic=topic,
func=func, params=params, statement=statement.strip(),
solution=solution.strip(), complexity=complexity,
hints=list(hints), fixed=list(fixed), rand=rand,
n_random=n_random, notes=notes, starter=starter,
ref=ns[func])
BANK.append(prob)
return prob
def rl(rng, n=None, lo=-50, hi=50):
n = n if n is not None else rng.randint(1, 12)
return [rng.randint(lo, hi) for _ in range(n)]
def rgrid(rng, choices, min_side=1, max_side=4):
"""A RECTANGULAR random grid (same width on every row)."""
rows = rng.randint(min_side, max_side)
cols = rng.randint(min_side, max_side)
return [[rng.choice(choices) for _ in range(cols)] for _ in range(rows)]
# ============================================================================
# CODILITY — the official lesson tasks people actually get asked
# ============================================================================
P("binary_gap", "Binary Gap", "Easy", "Bit tricks", "solution", "n", """
A binary gap in a positive integer N is a maximal run of consecutive ZEROS that
is surrounded by ones at both ends in N's binary representation.
9 = 1001 -> one gap of length 2 -> 2
529 = 1000010001 -> gaps of 4 and 3 -> 4
20 = 10100 -> one gap of length 1 -> 1 (the trailing zero doesn't count)
15 = 1111 -> no gap -> 0
32 = 100000 -> no gap (never closed) -> 0
Write solution(n) returning the length of the longest binary gap, or 0 if there
is none. 1 <= n <= 2,147,483,647.
""", '''def solution(n):
bits = bin(n)[2:]
best = current = 0
counting = False
for bit in bits:
if bit == "1":
if counting:
best = max(best, current)
counting = True
current = 0
elif counting:
current += 1
return best
''', "O(log n)",
["bin(n)[2:] gives the binary digits as a string",
"Only start counting zeros AFTER you have seen a 1",
"A run only counts when it is CLOSED by another 1 — trailing zeros are ignored"],
fixed=[(9,), (529,), (20,), (15,), (32,), (1041,), (1,)],
rand=lambda rng: (rng.randint(1, 2 ** 30),),
notes="Codility Lesson 1. The trap is the unterminated trailing run of zeros.")
P("cyclic_rotation", "Cyclic Rotation", "Easy", "Arrays", "solution", "a, k", """
Rotate the array `a` to the RIGHT `k` times. Each rotation moves the last
element to the front.
solution([3, 8, 9, 7, 6], 3) -> [9, 7, 6, 3, 8]
solution([1, 2, 3, 4], 4) -> [1, 2, 3, 4]
solution([], 5) -> []
k can be larger than len(a). Return a NEW list.
""", '''def solution(a, k):
if not a:
return []
k %= len(a)
return a[-k:] + a[:-k] if k else a[:]
''', "O(n)",
["k % len(a) collapses the redundant full turns",
"A right rotation by k is a[-k:] + a[:-k]",
"Guard the empty list (modulo by zero!) and k == 0 (a[-0:] is the WHOLE list)"],
fixed=[([3, 8, 9, 7, 6], 3), ([1, 2, 3, 4], 4), ([], 5), ([1], 7), ([0, 0, 0], 1)],
rand=lambda rng: (rl(rng, rng.randint(0, 10), -20, 20), rng.randint(0, 15)),
notes="Codility Lesson 2. a[-0:] returning everything is the classic bug here.")
P("odd_occurrences", "Odd Occurrences In Array", "Easy", "Bit tricks", "solution", "a", """
The array has an ODD number of elements. Every value occurs an even number of
times except exactly one, which occurs an odd number of times.
Find that unpaired value.
solution([9, 3, 9, 3, 9, 7, 9]) -> 7
O(n) time and O(1) space is expected — so no dict, no set.
""", '''def solution(a):
result = 0
for value in a:
result ^= value
return result
''', "O(n) time, O(1) space",
["XOR: x ^ x == 0 and x ^ 0 == x",
"XOR is commutative, so the pairs cancel no matter the order",
"Fold the whole array with ^ and whatever survives is the odd one"],
fixed=[([9, 3, 9, 3, 9, 7, 9],), ([42],), ([1, 1, 2, 2, 5],)],
rand=lambda rng: (_odd_array(rng),),
notes="Codility Lesson 2. XOR is the O(1)-space trick they are testing for.")
def _odd_array(rng):
pairs = [rng.randint(1, 100) for _ in range(rng.randint(1, 6))]
lonely = rng.randint(101, 200)
arr = pairs + pairs + [lonely]
rng.shuffle(arr)
return arr
P("frog_jmp", "Frog Jump", "Easy", "Math", "solution", "x, y, d", """
A small frog is at position X and wants to reach at least position Y. It jumps
a fixed distance D each time.
Write solution(x, y, d) returning the MINIMUM number of jumps needed.
solution(10, 85, 30) -> 3
solution(10, 10, 5) -> 0
X <= Y, and the numbers go up to 1,000,000,000 — so a loop would time out.
Compute it with arithmetic.
""", '''def solution(x, y, d):
gap = y - x
return -(-gap // d)
''', "O(1)",
["distance = y - x",
"You need ceil(distance / d) jumps",
"Integer ceiling division without floats: -(-a // b)"],
fixed=[(10, 85, 30), (10, 10, 5), (1, 1000000000, 1), (0, 7, 3)],
rand=lambda rng: (lambda x, d: (x, x + rng.randint(0, 10 ** 6), d))(
rng.randint(1, 1000), rng.randint(1, 1000)),
notes="Codility Lesson 3. math.ceil on floats loses precision at 1e9 — use -(-a // b).")
P("perm_missing", "Permutation Missing Element", "Easy", "Math", "solution", "a", """
The array contains N distinct integers from the range 1..(N+1) — exactly one
value from that range is missing.
Find it.
solution([2, 3, 1, 5]) -> 4
solution([]) -> 1
Expected: O(n) time, O(1) space. Do NOT sort.
""", '''def solution(a):
n = len(a)
return (n + 1) * (n + 2) // 2 - sum(a)
''', "O(n) time, O(1) space",
["The full range 1..N+1 sums to (N+1)(N+2)/2",
"Subtract the actual sum and the missing number falls out",
"XOR-ing 1..N+1 against the array works too"],
fixed=[([2, 3, 1, 5],), ([],), ([1],), ([2],)],
rand=lambda rng: (_perm_missing(rng),),
notes="Codility Lesson 3. Gauss' sum formula, not a loop over a `seen` array.")
def _perm_missing(rng):
n = rng.randint(0, 12)
full = list(range(1, n + 2))
full.pop(rng.randrange(len(full)))
rng.shuffle(full)
return full
P("tape_equilibrium", "Tape Equilibrium", "Easy", "Prefix sums", "solution", "a", """
Split the array at position P (1 <= P < N) into a[0..P-1] and a[P..N-1].
The difference is |sum(left) - sum(right)|.
Return the MINIMAL difference achievable.
solution([3, 1, 2, 4, 3]) -> 1 (split after 3,1,2 -> |6 - 7| = 1)
N >= 2 and up to 100,000, so recomputing both sums for every P (O(n^2)) times
out. One pass.
""", '''def solution(a):
total = sum(a)
left = 0
best = None
for i in range(len(a) - 1):
left += a[i]
diff = abs(left - (total - left))
best = diff if best is None else min(best, diff)
return best
''', "O(n)",
["total = sum(a) once, before the loop",
"right = total - left, so you never re-sum",
"P runs from 1 to N-1 — the loop index goes to len(a) - 2"],
fixed=[([3, 1, 2, 4, 3],), ([1, 1],), ([-1000, 1000],), ([1, 2],)],
rand=lambda rng: (rl(rng, rng.randint(2, 15), -100, 100),),
notes="Codility Lesson 3. The canonical 'derive the right side from the total' pattern.")
P("frog_river", "Frog River One", "Easy", "Hash map", "solution", "x, a", """
A frog wants to cross a river to position X. Leaves fall: a[k] is the position
where a leaf falls at time k. The frog can cross once every position 1..X has
at least one leaf.
Return the EARLIEST time (index into a) when that happens, or -1 if it never does.
solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) -> 6
solution(1, [2, 2, 2]) -> -1
""", '''def solution(x, a):
seen = set()
for time, position in enumerate(a):
if position <= x and position not in seen:
seen.add(position)
if len(seen) == x:
return time
return -1
''', "O(n)",
["Track covered positions in a set",
"Stop the moment len(seen) == x — that index is the answer",
"Ignore positions greater than x"],
fixed=[(5, [1, 3, 1, 4, 2, 3, 5, 4]), (1, [2, 2, 2]), (1, [1]), (3, [1, 2])],
rand=lambda rng: (lambda x: (x, [rng.randint(1, x + 1) for _ in range(rng.randint(1, 20))]))(
rng.randint(1, 6)),
notes="Codility Lesson 4. Counting how many distinct targets are covered, not sorting.")
P("perm_check", "Permutation Check", "Easy", "Hash map", "solution", "a", """
Return 1 if the array is a permutation of 1..N (each value exactly once),
otherwise 0.
solution([4, 1, 3, 2]) -> 1
solution([4, 1, 3]) -> 0
""", '''def solution(a):
n = len(a)
return 1 if set(a) == set(range(1, n + 1)) else 0
''', "O(n)",
["A permutation of 1..N has exactly N distinct values",
"set(a) == set(range(1, len(a) + 1)) settles it in one line",
"Watch out for duplicates AND out-of-range values"],
fixed=[([4, 1, 3, 2],), ([4, 1, 3],), ([1],), ([2],), ([1, 1],)],
rand=lambda rng: (_perm_check_case(rng),),
notes="Codility Lesson 4.")
def _perm_check_case(rng):
n = rng.randint(1, 10)
arr = list(range(1, n + 1))
rng.shuffle(arr)
if rng.random() < 0.5:
arr[rng.randrange(n)] = rng.randint(1, n + 3)
return arr
P("missing_integer", "Missing Integer", "Medium", "Hash map", "solution", "a", """
Return the SMALLEST positive integer (>= 1) that does NOT occur in the array.
solution([1, 3, 6, 4, 1, 2]) -> 5
solution([1, 2, 3]) -> 4
solution([-1, -3]) -> 1
The array may contain negatives and duplicates. O(n) expected.
""", '''def solution(a):
present = set(a)
candidate = 1
while candidate in present:
candidate += 1
return candidate
''', "O(n)",
["Put everything in a set first so lookups are O(1)",
"Then walk 1, 2, 3, ... until you find a gap",
"The answer is at most len(a) + 1, so the loop is bounded"],
fixed=[([1, 3, 6, 4, 1, 2],), ([1, 2, 3],), ([-1, -3],), ([],), ([2],)],
rand=lambda rng: (rl(rng, rng.randint(1, 15), -5, 15),),
notes="Codility Lesson 4. The answer can never exceed N+1 — that bounds the scan.")
P("max_counters", "Max Counters", "Medium", "Arrays", "solution", "n, a", """
You have N counters, all starting at 0. For each value K in the operations list:
* if 1 <= K <= N: increase counter K by 1
* if K == N + 1: set ALL counters to the current maximum
Return the final counters as a list.
solution(5, [3, 4, 4, 6, 1, 4, 4]) -> [3, 2, 2, 4, 2]
N and len(a) go up to 100,000. Actually writing to every counter on a max_counter
operation is O(n*m) and WILL time out — that is the whole point of this task.
""", '''def solution(n, a):
counters = [0] * n
floor = 0 # every counter is at least this
current_max = 0
for op in a:
if op == n + 1:
floor = current_max
else:
i = op - 1
counters[i] = max(counters[i], floor) + 1
current_max = max(current_max, counters[i])
return [max(value, floor) for value in counters]
''', "O(n + m)",
["Do NOT loop over all counters on a max-op — that is the trap",
"Keep a lazy `floor` value that every counter is implicitly raised to",
"When you touch a counter, first lift it: max(counter, floor), then +1",
"At the very end, lift everything that was never touched"],
fixed=[(5, [3, 4, 4, 6, 1, 4, 4]), (1, [1, 2, 1]), (3, [4, 4, 4]), (2, [])],
rand=lambda rng: (lambda n: (n, [rng.randint(1, n + 1) for _ in range(rng.randint(0, 20))]))(
rng.randint(1, 8)),
notes="Codility Lesson 4. Lazy propagation — the single most-failed Codility task.")
P("count_div", "Count Div", "Easy", "Math", "solution", "a, b, k", """
Count the integers in the inclusive range [a, b] that are divisible by k.
solution(6, 11, 2) -> 3 (6, 8, 10)
solution(0, 0, 11) -> 1 (0 is divisible by everything)
a and b go up to 2,000,000,000 so a loop is far too slow. O(1) arithmetic.
""", '''def solution(a, b, k):
return b // k - (a - 1) // k if a > 0 else b // k + 1
''', "O(1)",
["Multiples of k up to x: x // k",
"So the answer is b//k - (a-1)//k",
"a == 0 is the special case: zero itself counts, and (0-1)//k is -1"],
fixed=[(6, 11, 2), (0, 0, 11), (0, 10, 3), (1, 1, 1), (11, 345, 17)],
rand=lambda rng: (lambda a: (a, a + rng.randint(0, 10 ** 6), rng.randint(1, 1000)))(
rng.randint(0, 10 ** 6)),
notes="Codility Lesson 5. Pure counting arithmetic; the a == 0 edge case is the trap.")
P("passing_cars", "Passing Cars", "Easy", "Prefix sums", "solution", "a", """
An array of 0s and 1s: 0 = a car driving EAST, 1 = a car driving WEST.
A pair (P, Q) passes each other when P < Q, a[P] == 0 and a[Q] == 1.
Return the number of passing pairs, or -1 if it exceeds 1,000,000,000.
solution([0, 1, 0, 1, 1]) -> 5
O(n) — counting pairs with a nested loop is O(n^2) and times out at N = 100,000.
""", '''def solution(a):
east = 0
pairs = 0
for value in a:
if value == 0:
east += 1
else:
pairs += east
if pairs > 1000000000:
return -1
return pairs
''', "O(n)",
["Sweep left to right counting the 0s seen so far",
"Every time you meet a 1, it pairs with ALL of those 0s at once",
"Bail out as soon as the running total exceeds 1e9"],
fixed=[([0, 1, 0, 1, 1],), ([],), ([1, 1, 1],), ([0, 0, 0],), ([0, 1],)],
rand=lambda rng: ([rng.randint(0, 1) for _ in range(rng.randint(0, 20))],),
notes="Codility Lesson 5. 'Count how many of the other kind came before' — a core pattern.")
P("min_avg_slice", "Min Avg Two Slice", "Medium", "Prefix sums", "solution", "a", """
A slice is a contiguous chunk a[p..q] with p < q. Return the STARTING index of
the slice with the smallest average. If several tie, return the smallest index.
solution([4, 2, 2, 5, 1, 5, 8]) -> 1 (slice [2,2], average 2)
Key insight: you never need to check slices longer than 3. Any longer slice can
be split into 2- and 3-slices, and at least one of them has an average no worse
than the whole. So checking every 2-slice and 3-slice is enough — O(n).
""", '''def solution(a):
n = len(a)
best_index = 0
best_avg = (a[0] + a[1]) / 2
for i in range(n - 1):
avg2 = (a[i] + a[i + 1]) / 2
if avg2 < best_avg:
best_avg, best_index = avg2, i
if i < n - 2:
avg3 = (a[i] + a[i + 1] + a[i + 2]) / 3
if avg3 < best_avg:
best_avg, best_index = avg3, i
return best_index
''', "O(n)",
["Only slices of length 2 and 3 can be minimal — prove it to yourself, then use it",
"One pass, comparing both windows at each index",
"Use strict < so ties keep the earliest index"],
fixed=[([4, 2, 2, 5, 1, 5, 8],), ([1, 1],), ([-3, -5, -8, -4, -10],), ([5, 1, 1, 5],)],
rand=lambda rng: (rl(rng, rng.randint(2, 12), -20, 20),),
notes="Codility Lesson 5. The 'length 2 or 3 is enough' lemma is the entire task.")
P("distinct", "Distinct", "Easy", "Sorting", "solution", "a", """
Return the number of DISTINCT values in the array.
solution([2, 1, 1, 2, 3, 1]) -> 3
solution([]) -> 0
""", '''def solution(a):
return len(set(a))
''', "O(n) with a set / O(n log n) sorted",
["len(set(a)) is the whole answer",
"Codility's official approach sorts and counts changes — both are accepted"],
fixed=[([2, 1, 1, 2, 3, 1],), ([],), ([7],), ([1, 1, 1],)],
rand=lambda rng: (rl(rng, rng.randint(0, 20), -5, 5),),
notes="Codility Lesson 6. Free points — but say the complexity out loud.")
P("triangle", "Triangle", "Easy", "Sorting", "solution", "a", """
Return 1 if the array contains a triangular triplet (indices p < q < r with
a[p] + a[q] > a[r], a[q] + a[r] > a[p], a[r] + a[p] > a[q]), otherwise 0.
solution([10, 2, 5, 1, 8, 20]) -> 1 (10, 8, 20)
solution([10, 50, 5, 1]) -> 0
O(n log n): sort, then only ADJACENT triples can possibly work.
""", '''def solution(a):
ordered = sorted(a)
for i in range(len(ordered) - 2):
if ordered[i] + ordered[i + 1] > ordered[i + 2]:
return 1
return 0
''', "O(n log n)",
["Sort first — then two of the three conditions are automatically true",
"Only consecutive triples matter: a wider gap only makes the sum condition harder",
"Watch out for overflow-free comparison: a[i] + a[i+1] > a[i+2]"],
fixed=[([10, 2, 5, 1, 8, 20],), ([10, 50, 5, 1],), ([],), ([1, 1, 1],), ([1, 2, 3],)],
rand=lambda rng: (rl(rng, rng.randint(0, 10), 1, 40),),
notes="Codility Lesson 6. Sorting turns three conditions into one.")
P("max_product_three", "Max Product Of Three", "Medium", "Sorting", "solution", "a", """
Return the maximum product of any three values in the array.
solution([-3, 1, 2, -2, 5, 6]) -> 60 (2 * 5 * 6)
solution([-5, -6, 1, 2, 3]) -> 90 (-5 * -6 * 3)
The trap is negatives: two big negatives multiply into a big positive.
""", '''def solution(a):
ordered = sorted(a)
return max(ordered[-1] * ordered[-2] * ordered[-3],
ordered[0] * ordered[1] * ordered[-1])
''', "O(n log n)",
["Sort, then there are only TWO candidates",
"Either the three largest, or the two smallest (most negative) times the largest",
"max() of those two candidates is the answer"],
fixed=[([-3, 1, 2, -2, 5, 6],), ([-5, -6, 1, 2, 3],), ([1, 2, 3],),
([-1, -2, -3],), ([0, 0, 0, 5],)],
rand=lambda rng: (rl(rng, rng.randint(3, 12), -30, 30),),
notes="Codility Lesson 6. Also a very common phone-screen question.")
P("brackets", "Brackets", "Medium", "Stack", "solution", "s", """
Return 1 if the string of brackets is properly nested, otherwise 0.
The string can contain ( ) [ ] { }.
solution("{[()()]}") -> 1
solution("([)()]") -> 0
solution("") -> 1
""", '''def solution(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return 0
return 1 if not stack else 0
''', "O(n)",
["A stack is the answer — push openers, pop on closers",
"If the popped opener does not match the closer, fail immediately",
"At the end the stack must be EMPTY, otherwise something never closed"],
fixed=[("{[()()]}",), ("([)()]",), ("",), ("(",), (")(",), ("{{{{",)],
rand=lambda rng: ("".join(rng.choice("()[]{}") for _ in range(rng.randint(0, 10))),),
notes="Codility Lesson 7 == LeetCode 'Valid Parentheses'. Learn this one cold.")
P("fish", "Fish", "Medium", "Stack", "solution", "a, b", """
N fish flow down a river. a[i] is the size of fish i, b[i] its direction:
0 = upstream (flowing toward smaller indices), 1 = downstream.
When a downstream fish meets an upstream fish, the bigger one eats the smaller.
All sizes are distinct.
Return how many fish stay alive.
solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]) -> 2
""", '''def solution(a, b):
downstream = []
alive = 0
for size, direction in zip(a, b):
if direction == 1:
downstream.append(size)
else:
while downstream and downstream[-1] < size:
downstream.pop()
if not downstream:
alive += 1
return alive + len(downstream)
''', "O(n)",
["Keep a stack of the downstream fish that are still swimming",
"An upstream fish fights the top of that stack until it wins or dies",
"If the stack empties, the upstream fish survives for good"],
fixed=[([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]), ([1], [0]), ([1, 2], [1, 0]),
([5, 1], [1, 0]), ([], [])],
rand=lambda rng: (lambda n: (rng.sample(range(1, 100), n),
[rng.randint(0, 1) for _ in range(n)]))(rng.randint(0, 8)),
notes="Codility Lesson 7. Same skeleton as 'Asteroid Collision' on LeetCode.")
P("stone_wall", "Stone Wall", "Medium", "Stack", "solution", "h", """
Build a wall whose height at position i must be exactly h[i]. Each stone is a
rectangle of any width but constant height. Return the MINIMUM number of stones.
solution([8, 8, 5, 7, 9, 8, 7, 4, 8]) -> 7
""", '''def solution(h):
stack = []
stones = 0
for height in h:
while stack and stack[-1] > height:
stack.pop()
if not stack or stack[-1] < height:
stack.append(height)
stones += 1
return stones
''', "O(n)",
["A monotonically increasing stack of the heights currently 'open'",
"Pop everything taller than the current height — those stones are finished",
"If the top equals the current height, reuse that stone (no new count)"],
fixed=[([8, 8, 5, 7, 9, 8, 7, 4, 8],), ([],), ([1],), ([1, 1, 1],), ([1, 2, 3, 2, 1],)],
rand=lambda rng: (rl(rng, rng.randint(0, 12), 1, 10),),
notes="Codility Lesson 7. Monotonic stack — the same idea as 'Largest Rectangle in Histogram'.")
P("dominator", "Dominator", "Medium", "Counting", "solution", "a", """
The dominator of an array is a value occurring in MORE than half the positions.
Return ANY index holding the dominator, or -1 if there is none.
solution([3, 4, 3, 2, 3, -1, 3, 3]) -> any index where the value is 3
solution([1, 2]) -> -1
Expected O(n) time, O(1) space -> Boyer-Moore voting.
""", '''def solution(a):
candidate = None
count = 0
for value in a:
if count == 0:
candidate, count = value, 1
elif value == candidate:
count += 1
else:
count -= 1
if candidate is None:
return -1
occurrences = a.count(candidate)
if occurrences * 2 <= len(a):
return -1
return a.index(candidate)
''', "O(n) time, O(1) space",
["Boyer-Moore: hold one candidate and a counter; matching votes +1, others -1",
"When the counter hits 0, adopt the current value as the new candidate",
"You MUST verify the survivor at the end — the vote only finds a candidate"],
fixed=[([3, 4, 3, 2, 3, -1, 3, 3],), ([1, 2],), ([],), ([7],), ([1, 1, 2],)],
rand=lambda rng: (_dominator_case(rng),),
notes="Codility Lesson 8 == LeetCode 'Majority Element'. The verification step is not optional.",
# any index of the dominator is accepted
)
_DOMINATOR_CHECK = '''
def check(args, got):
a = args[0]
if not a:
return got == -1
counts = {}
for v in a:
counts[v] = counts.get(v, 0) + 1
best = max(counts, key=lambda k: counts[k])
if counts[best] * 2 <= len(a):
return got == -1
return isinstance(got, int) and 0 <= got < len(a) and a[got] == best
'''
BANK[-1].checker_src = _DOMINATOR_CHECK # type: ignore[attr-defined]
def _dominator_case(rng):
n = rng.randint(1, 12)
if rng.random() < 0.6:
dom = rng.randint(1, 5)
arr = [dom] * (n // 2 + 1) + [rng.randint(6, 9) for _ in range(n - n // 2 - 1)]
else:
arr = [rng.randint(1, 9) for _ in range(n)]
rng.shuffle(arr)
return arr
P("max_profit", "Max Profit", "Easy", "Greedy", "solution", "a", """
a[i] is a share price on day i. Buy on one day, sell on a LATER day.
Return the maximum profit, or 0 if no profitable trade exists.
solution([23171, 21011, 21123, 21366, 21013, 21367]) -> 356
solution([5, 4, 3]) -> 0
One pass, O(n).
""", '''def solution(a):
best = 0
cheapest = None
for price in a:
if cheapest is None or price < cheapest:
cheapest = price
else:
best = max(best, price - cheapest)
return best
''', "O(n)",
["Track the cheapest price seen so far",
"At every day, the best sale today is price - cheapest",
"Never let the profit go below 0"],
fixed=[([23171, 21011, 21123, 21366, 21013, 21367],), ([5, 4, 3],), ([],), ([1],),
([1, 2, 3, 4],)],
rand=lambda rng: (rl(rng, rng.randint(0, 15), 1, 200),),
notes="Codility Lesson 9 == LeetCode 121 'Best Time to Buy and Sell Stock'.")
P("max_slice_sum", "Max Slice Sum (Kadane)", "Medium", "Dynamic programming",
"solution", "a", """
Return the maximum sum of any NON-EMPTY contiguous slice.
solution([3, 2, -6, 4, 0]) -> 5
solution([-5, -2, -8]) -> -2
This is Kadane's algorithm. Note the array can be all-negative, so starting
`best = 0` is wrong.
""", '''def solution(a):
best = current = a[0]
for value in a[1:]:
current = max(value, current + value)
best = max(best, current)
return best
''', "O(n)",
["At each element decide: extend the current slice, or start fresh here",
"current = max(value, current + value)",
"Initialise BOTH best and current from a[0], not from 0"],
fixed=[([3, 2, -6, 4, 0],), ([-5, -2, -8],), ([1],), ([-1],), ([2, -1, 2, -1, 2],)],
rand=lambda rng: (rl(rng, rng.randint(1, 15), -20, 20),),
notes="Codility Lesson 9 == LeetCode 53 'Maximum Subarray'. Memorise the two lines.")
P("count_factors", "Count Factors", "Medium", "Math", "solution", "n", """
Return how many factors (divisors) the positive integer n has.
solution(24) -> 8 (1, 2, 3, 4, 6, 8, 12, 24)
solution(1) -> 1
n goes up to 2,147,483,647, so trial division up to n is far too slow.
Only go up to sqrt(n) and count both members of each pair.
""", '''def solution(n):
count = 0
i = 1
while i * i < n:
if n % i == 0:
count += 2
i += 1
if i * i == n:
count += 1
return count
''', "O(sqrt n)",
["Divisors come in pairs: if i divides n, so does n // i",
"Loop while i * i < n and add 2 for each hit",
"A perfect square has one unpaired divisor — handle i * i == n separately"],
fixed=[(24,), (1,), (36,), (2147483647,), (97,)],
rand=lambda rng: (rng.randint(1, 10 ** 6),),
notes="Codility Lesson 10. Use i*i < n, not i < sqrt(n) — no float rounding bugs.")
P("min_perimeter", "Min Perimeter Rectangle", "Medium", "Math", "solution", "n", """
Find the minimal perimeter of a rectangle with integer sides whose area is
exactly n.
solution(30) -> 22 (5 x 6)
solution(1) -> 4
Perimeter = 2 * (a + b) where a * b == n. The most "square" pair wins, so walk
down from sqrt(n).
""", '''def solution(n):
i = 1
best = None
while i * i <= n:
if n % i == 0:
best = 2 * (i + n // i)
i += 1
return best
''', "O(sqrt n)",
["Only check divisors up to sqrt(n)",
"The LAST divisor you find below sqrt(n) is the most square one",
"perimeter = 2 * (i + n // i)"],
fixed=[(30,), (1,), (36,), (101,), (1000000,)],
rand=lambda rng: (rng.randint(1, 10 ** 6),),
notes="Codility Lesson 10.")
P("chocolates", "Chocolates By Numbers", "Medium", "Math", "solution", "n, m", """
There are N chocolates in a circle, numbered 0..N-1. You eat chocolate 0, then
jump M forward each time (wrapping around), until you reach one you already ate.
Return how many you eat.
solution(10, 4) -> 5
The cycle length is n / gcd(n, m). Prove it, then it is a one-liner.
N and M go up to 1,000,000,000, so simulating the walk is not an option.
""", '''def solution(n, m):
x, y = n, m
while y:
x, y = y, x % y
return n // x
''', "O(log n)",
["Simulating is O(n) — too slow at 1e9",
"You visit exactly n // gcd(n, m) distinct chocolates",
"Implement Euclid's gcd with the while loop"],
fixed=[(10, 4), (1, 1), (947853, 4453), (10, 10), (13, 5)],
rand=lambda rng: (rng.randint(1, 10 ** 6), rng.randint(1, 10 ** 6)),
notes="Codility Lesson 12. Number theory disguised as a simulation.")
P("genomic_range", "Genomic Range Query", "Hard", "Prefix sums", "solution", "s, p, q", """
A DNA string of A, C, G, T. Each letter has an impact factor: A=1, C=2, G=3, T=4.
For each query (p[k], q[k]) — an inclusive slice of the string — return the
MINIMAL impact factor inside it.
solution("CAGCCTA", [2, 5, 0], [4, 5, 6]) -> [2, 4, 1]
There can be 50,000 queries over a 100,000-character string, so scanning each
slice is O(n*m) and times out. Build four prefix-count arrays instead: then each
query is O(1).
""", '''def solution(s, p, q):
n = len(s)
letters = "ACGT"
prefix = [[0] * (n + 1) for _ in range(4)]
for i, ch in enumerate(s):
for k in range(4):
prefix[k][i + 1] = prefix[k][i] + (1 if ch == letters[k] else 0)
out = []
for start, end in zip(p, q):
for k in range(4):
if prefix[k][end + 1] - prefix[k][start] > 0:
out.append(k + 1)
break
return out
''', "O(n + m)",
["Build one prefix-count array per letter: how many A's in s[0..i)",
"Count of letter k inside [start, end] = prefix[k][end+1] - prefix[k][start]",
"For each query, check A first, then C, then G, then T — the first non-zero wins"],
fixed=[("CAGCCTA", [2, 5, 0], [4, 5, 6]), ("A", [0], [0]), ("TTTT", [0, 1], [3, 2])],
rand=lambda rng: _genomic_case(rng),
notes="Codility Lesson 5 (hard). The 'prefix count per category' trick generalises a lot.")
def _genomic_case(rng):
s = "".join(rng.choice("ACGT") for _ in range(rng.randint(1, 20)))
n = len(s)
p, q = [], []
for _ in range(rng.randint(1, 5)):
a = rng.randrange(n)
b = rng.randrange(a, n)
p.append(a)
q.append(b)
return (s, p, q)
P("nesting", "Nesting", "Easy", "Stack", "solution", "s", """
Return 1 if the string of only ( and ) is properly nested, else 0.
solution("(()(())())") -> 1
solution("())") -> 0
solution("") -> 1
O(1) space: you only need a counter, not a stack.
""", '''def solution(s):
depth = 0
for ch in s:
depth += 1 if ch == "(" else -1
if depth < 0:
return 0
return 1 if depth == 0 else 0
''', "O(n) time, O(1) space",
["A single depth counter is enough when there is only one bracket type",
"If the depth ever goes negative, a ) came too early",
"It must end at exactly 0"],
fixed=[("(()(())())",), ("())",), ("",), ("(",), ("()()",)],
rand=lambda rng: ("".join(rng.choice("()") for _ in range(rng.randint(0, 12))),),
notes="Codility Lesson 7. The counter version is the answer they want.")
P("number_of_disc", "Number Of Disc Intersections", "Hard", "Sorting", "solution", "a", """
Disc i is centred at (i, 0) with radius a[i]. Two discs intersect if they touch
or overlap.
Return the number of intersecting PAIRS, or -1 if it exceeds 10,000,000.
solution([1, 5, 2, 1, 4, 0]) -> 11
The O(n^2) pairwise check times out at N = 100,000. Sort the interval starts and
ends, then sweep: at each start, every disc still open intersects it.
""", '''def solution(a):
starts = sorted(i - r for i, r in enumerate(a))
ends = sorted(i + r for i, r in enumerate(a))
pairs = 0
open_discs = 0
j = 0
for start in starts:
while j < len(ends) and ends[j] < start:
open_discs -= 1
j += 1
pairs += open_discs
open_discs += 1
if pairs > 10000000:
return -1
return pairs
''', "O(n log n)",
["Turn each disc into an interval [i - r, i + r]",
"Sort starts and ends separately, then sweep with two pointers",
"When a new disc opens, it intersects every disc still open"],
fixed=[([1, 5, 2, 1, 4, 0],), ([],), ([0, 0],), ([1, 1],), ([0],)],
rand=lambda rng: (rl(rng, rng.randint(0, 12), 0, 10),),
notes="Codility Lesson 6 (hard). The sweep-line pattern shows up in calendar/meeting problems too.")
P("equi_leader", "Equi Leader", "Medium", "Counting", "solution", "a", """
A leader of an array is a value occurring in more than half its positions.
An equi leader is an index S such that a[0..S] and a[S+1..n-1] have the SAME
leader.
Return how many equi leaders exist.
solution([4, 3, 4, 4, 4, 2]) -> 2
""", '''def solution(a):
n = len(a)
candidate, count = None, 0
for value in a:
if count == 0:
candidate, count = value, 1
elif value == candidate:
count += 1
else:
count -= 1
if candidate is None:
return 0
total = a.count(candidate)
if total * 2 <= n:
return 0
equi = 0
left = 0
for i in range(n - 1):
if a[i] == candidate:
left += 1
if left * 2 > i + 1 and (total - left) * 2 > n - i - 1:
equi += 1
return equi
''', "O(n)",
["Only the array's own leader can be the leader of both halves",
"Find it with Boyer-Moore, then verify it really is a leader",
"Sweep once keeping the count in the left part; the right count is total - left"],
fixed=[([4, 3, 4, 4, 4, 2],), ([],), ([1, 1],), ([1, 2],), ([2, 2, 2, 2],)],
rand=lambda rng: (_dominator_case(rng),),
notes="Codility Lesson 8. Combines Boyer-Moore with a prefix sweep.")
# ============================================================================
# LEETCODE PATTERNS
# ============================================================================
P("two_sum", "Two Sum", "Easy", "Hash map", "two_sum", "nums, target", """
Return the INDICES of the two numbers that add up to target, as a list
[i, j] with i < j. Exactly one solution exists and you may not reuse an element.
two_sum([2, 7, 11, 15], 9) -> [0, 1]
two_sum([3, 3], 6) -> [0, 1]
O(n) with a dict of value -> index. The O(n^2) double loop is the "no" answer.
""", '''def two_sum(nums, target):
seen = {}
for i, value in enumerate(nums):
if target - value in seen:
return [seen[target - value], i]
seen[value] = i
return []
''', "O(n)",
["Store value -> index as you go",
"For each value ask whether target - value was already seen",
"Insert AFTER the lookup so an element cannot pair with itself"],
fixed=[([2, 7, 11, 15], 9), ([3, 3], 6), ([3, 2, 4], 6), ([-1, -2, -3], -5)],
rand=lambda rng: _two_sum_case(rng),
notes="LeetCode 1. The most-asked question in existence — never miss it.")
def _two_sum_case(rng):
nums = rng.sample(range(-40, 60), rng.randint(2, 10))
i, j = sorted(rng.sample(range(len(nums)), 2))
return (nums, nums[i] + nums[j])
P("valid_parens", "Valid Parentheses", "Easy", "Stack", "is_valid", "s", """
Given a string of just ()[]{}, decide whether every bracket is closed by the
same type, in the right order.
is_valid("()[]{}") -> True
is_valid("(]") -> False
is_valid("([)]") -> False
""", '''def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
''', "O(n)",
["Push openers onto a stack",
"On a closer, the popped item must be its matching opener",
"Empty stack at the end = valid"],
fixed=[("()[]{}",), ("(]",), ("([)]",), ("",), ("{[]}",)],
rand=lambda rng: ("".join(rng.choice("()[]{}") for _ in range(rng.randint(0, 10))),),
notes="LeetCode 20.")
P("max_subarray", "Maximum Subarray", "Medium", "Dynamic programming",
"max_subarray", "nums", """
Return the largest sum of a contiguous non-empty subarray.
max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) -> 6 ([4, -1, 2, 1])
max_subarray([-1]) -> -1
""", '''def max_subarray(nums):
best = current = nums[0]
for value in nums[1:]:
current = max(value, current + value)
best = max(best, current)
return best
''', "O(n)",
["Kadane's algorithm",
"current = max(value, current + value) — restart or extend",
"All-negative input means you cannot start at 0"],
fixed=[([-2, 1, -3, 4, -1, 2, 1, -5, 4],), ([-1],), ([5, 4, -1, 7, 8],), ([1],)],
rand=lambda rng: (rl(rng, rng.randint(1, 15), -15, 15),),
notes="LeetCode 53.")
P("product_except_self", "Product of Array Except Self", "Medium", "Prefix sums",
"product_except_self", "nums", """
Return a list where out[i] is the product of every element EXCEPT nums[i].
product_except_self([1, 2, 3, 4]) -> [24, 12, 8, 6]
product_except_self([-1, 1, 0, -3, 3]) -> [0, 0, 9, 0, 0]
You must do it WITHOUT division, in O(n).