Working through code problems in OCaml.
Or, parlour tricks for the technical interview rigmarole.
All the problems are in src/
, and loosely organised into categories below.
Each problem comprises a brief description, a solution program, and a test. (See Usage for instructions on how to build and run the tests.)
- Array pair sum
- Even-occurring element
- Integer difference
- Largest continuous sum
- Longest common prefix
- Longest words
- Missing element
- Odd-occurring element
- Sum of list plus one
- Sum of multiples
- Anagram detection
- Balanced brackets
- Byte format
- Combine two strings
- CSV parse
- First non-repeated character
- Integer length
- Largest palindrome
- Money format
- Number format
- Remove duplicate characters
- Reverse words
- String format
- String permutations
- String rotation
- Only use the OCaml standard library.
- Memoise/cache all the things! (Or at least when we absolutely must do so, anyway.) The
Hashtbl
module is your friend. - Top-level functions should not be recursive. Instead, use an auxiliary recursive function inside the top-level function.
- If we’re writing a recursive function (which is probably most of the time), try as far as possible to write it such that it is tail recursive.
- For readability, annotate the arguments and return type of all top-level functions.
- Short-circuit execution by throwing an exception.
- Avoid mutable variables if possible.
Use short variable names if we are dealing with very few variables, or if the meaning is obvious (or can be intuitively inferred). Some general conventions:
- Auxiliary function —
aux
- List —
xs
(orys
,zs
) - Items in a list —
x
(ory
,z
) - List for accumulating values —
acc
- Binary tree — value
v
(orw
) with al
subtree and ar
subtree - String —
str
- Integer —
n
(orm
) - Length of a string or list —
len
If there is ambiguity (eg. when we are dealing with many variables of the same type), use more descriptive names in snake_case
.
First, install ocamlfind, oUnit (for tests), and Bisect (for test coverage) with OPAM:
$ opam install ocamlfind ounit bisect
Then, grab this repository:
$ git clone https://github.com/yuanqing/code-problems
$ cd code-problems/src
$ make
Use make coverage
to run the tests and generate coverage reports (output to coverage/
).
…for example, for the binary search problem:
$ make binary_search/test
Use make binary_search/coverage
to run the test and generate coverage reports (output to coverage/
).
To remove all compiled files and other debris:
$ make clean
- The Bisect test coverage does not appear to be completely accurate.
The bulk of the problems are from the code-problems project maintained by Blake Embrey.
All solution programs in this repository were written by me.