You are on page 1of 2

Google Code Jam Cheat Sheet

http://blog.benoitblanchon.fr/ - v1.0

Algorithm design
Ask yourself before coding

Is a suboptimal solution accepted, i.e. can you use a heuristic?


If so, what input would fool your heuristic? Is it acceptable?
Can you divide the problem into smaller ones?
Can you build the answer from a base case, like N=1?
Would it be easier if the data was sorted?

Classic algorithms and techniques


1.
2.
3.
4.
5.
6.
7.

Brute force / Backtracking


Graph/Tree traversal: BFS and DFS
Divide and Conquer / Binary Search
Base case and build
Dynamic programming (cache and reuse data)
Path finding (e.g A*, Dijkstra)
Heuristics (e.g greedy algorithm)

Your implementation is too slow?


1. Are you visiting the same graph node several time?
2. Can you save the intermediate results to avoid computing the same thing again and
again?
3. Can you pre-compute some useful data?
4. Can you quickly eliminate a large set of candidate solutions (pruning)?

Maximum problem size, depending on complexity


Complexit
y
N max

log n

n log n

n2

n3

2n

n!

109

108

104

103

30

10

Data type limits


int

2.10

Long
9

9. 10

BigInteger
18

doubles
308

10

decimal
28

10

, 15

digits

digits

Mathematics
Quadratic equation
ax 2+ bx+ c=0

=b2 4 ac

x=

b
2a

Combinations or Sets (order is ignored)


k elements among n

Number of pairs

, 28

With repeated
elements:

Cnk =

n!
k !(nk )!

C2n =

n(n1)
2

kn =Ckn +k1

Permutations (order counts)


k elements among n
n!
A kn=
(nk )!

Number of permutations
n
A n=n!

Probability
A and B
P ( A B ) =P ( B| A ) . P (A )

A or B
A knowing B (Bayes
P ( A B )=P ( A ) + P ( B )P( A theorem)
B)
P ( B| A ) P( A)
P ( A|B )=
P( B)

Workaround the accuracy of floating point values


A B=eln A +ln B

A
=e ln A ln B
B

Dont do strict comparisons.


Accept a small error
(epsilon).

Prime numbers
function gcd(a, b)
while b 0
t := b
b := a mod b
a := t
return a

gcd ( a , b ) lcm ( a ,b )=a b Coprime


gcd ( a , b )=1

Stuck?
1. Read the problem again, make sure you leverage every piece of information
(including the limits, the problem size and the statistics)
2. Try to solve by hand
3. Watch carefully the results and look for a pattern
4. Still nothing? Keep 30 to 60 minutes for the brute force implementation.

Before you send your solution


1. Read the problem again, make sure there is no misunderstanding
2. Look at the statistics.
If some people fails (< 90% success), you should look for the pitfall.
If many people fails (< 70% success), you may consider skipping the problem.
3. Forget about the O(n!), its doomed to fail
4. Assert everything (input, output and intermediate values) if something goes wrong
youll detect and fix the bug within the 4 minutes
5. Add samples to the input file: singular case (zero, negative) and extreme cases
6. Remove all unused code and clean everything that stays in your program

You might also like