Skip to content

Two Sum

Algorithmic — Given an array and a target sum, find two numbers that add up to it.

Tests: HashMap, iteration, returning a compound value.

Results

Language Lines Tokens Verbosity Tok/Line Sym/Line Concepts Safety Ceremony
Python7311464.434.4363.80
Clojure8361824.55.2554.30
Ruby8251113.13353.80.25
Kotlin9391934.334.6773.90.222
Haskell10583205.84.7114.80.2
Javascript10361733.64.662.30.3
Swift11462404.184.2784.30.273
Typescript11452334.095.7383.30.273
C126031055.17700.583
Erlang124825746.6754.70
Go12442163.673.2573.50.333
Rust12432193.585.25134.80.333
Elixir13422153.234.15650.231
Zig13482553.695.08133.30.385
Objc14593204.216.5760.80.214
Cpp15542893.65.661.10.4
Java15532823.534.67103.10.467
Csharp16542913.383.7583.70.438
Milo18854824.7251550.389

Observations

Simple problem — all languages cluster near 7-15 LOC. Ruby wins on tokens and verbosity: each_with_index + implicit return + no type annotations = minimal syntax.

Haskell is interesting — only 10 lines but highest token count (58) due to pattern matching verbosity and qualified Map.lookup.

Python's enumerate() + dictionary lookup remains the gold standard for clarity.

Solutions

def two_sum(nums: list[int], target: int) -> tuple[int, int]:
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return (seen[complement], i)
        seen[n] = i