Day 1:Not Quite Lisp
Monoid reductions, prefix sums, and first-passage times on a 1D lattice path.
Santa is trying to deliver presents in a large apartment building, but he can’t find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.
An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.
— Advent of Code 2015, Day 1
Problem Model
The puzzle input is a single unbroken line of parentheses—nothing but ( and ), with no spaces or separators—such as (())).
Each character nudges a floor counter by one step:
(moves the counter up by1.)moves the counter down by1.
Written formally, the input is a finite string over the two-symbol alphabet , and each symbol maps to a step through a helper function :
Starting from ground floor , the floor after instructions is the -th partial sum:
Plot those floors over time and you get a 1D lattice path—the deterministic cousin of a 1D Simple Random Walk, a term Karl Pearson coined in 1905. When such a path starts at , ends at , and never dips below ground, mathematicians call it a Dyck path, named after Walther von Dyck.
Isolating in its own helper function keeps character parsing out of the main loop and lets both parts speak directly in terms of floor changes.
Part 1: Final Floor
To what floor do the instructions take Santa?
— Advent of Code 2015, Day 1
Theoretical Explanation
If you only care where Santa finishes, the route he took along the way disappears—only the net sum matters. That single observation opens the door to one of the most versatile patterns in computer science.
Reduction / Fold & Monoid Homomorphism
Collapsing a sequence into a single value with an associative binary operator is called a Fold / Reduction.
Why does addition work so cleanly here? Because the integers under addition form a commutative monoid: addition is associative, has an identity element (), and ignores order. As a result, is a monoid homomorphism from strings to :
That algebraic symmetry buys two practical payoffs:
- Order Independence & Parallelism: Since you can regroup and reorder additions freely, threads can sum separate chunks of the string and merge their totals in parallel time (Parallel Reduction).
- Counting Identity: When the input contains only
(and), the final floor simplifies to , so a high-performance implementation can simply count'('bytes with SIMD instructions.
Optimality Lower Bound
Could a clever trick beat linear time? Imagine an algorithm that skips even a single character in the string. An adversary could flip that unread character between ( and ), shifting by and forcing a wrong answer. Every sequential algorithm therefore needs at least time, which makes our time, space fold optimal.
Complexity Analysis
| Metric | Bound | Notes |
|---|---|---|
| Time | Tight . The algorithm must read every character. | |
| Space | The algorithm stores one integer, floor. |
Program Steps
- Set
floorto0. - For each character
chininput:- Calculate
d = stepDelta(ch)(+1for'(',-1for')',0otherwise). - Add
dtofloor.
- Calculate
- Return
floor.
Block Diagram
Implementation
Show Part 1 Implementation10 languages
static int step_delta(char ch) {
if (ch == '(') return 1;
if (ch == ')') return -1;
return 0;
}
int part1(const char *input) {
int floor = 0;
for (const char *p = input; *p != '\0'; p++) {
floor += step_delta(*p);
}
return floor;
}(defn step-delta [ch]
(case ch
\( 1
\) -1
0))
(defn part1 [input]
(reduce + 0 (map step-delta input)))package day01
func stepDelta(ch rune) int {
switch ch {
case '(':
return 1
case ')':
return -1
default:
return 0
}
}
func Part1(input string) int {
floor := 0
for _, ch := range input {
floor += stepDelta(ch)
}
return floor
}module Day01 (stepDelta, part1) where
import Data.Monoid (Sum (..))
stepDelta :: Char -> Int
stepDelta '(' = 1
stepDelta ')' = -1
stepDelta _ = 0
part1 :: String -> Int
part1 = getSum . foldMap (Sum . stepDelta)public class Day01Part1 {
static int stepDelta(char ch) {
return switch (ch) {
case '(' -> 1;
case ')' -> -1;
default -> 0;
};
}
public static int part1(String input) {
int floor = 0;
for (int i = 0; i < input.length(); i++) {
floor += stepDelta(input.charAt(i));
}
return floor;
}
}function stepDelta(ch) {
if (ch === '(') return 1;
if (ch === ')') return -1;
return 0;
}
export function part1(input) {
let floor = 0;
for (const ch of input) {
floor += stepDelta(ch);
}
return floor;
}local function step_delta(ch)
if ch == "(" then
return 1
elseif ch == ")" then
return -1
end
return 0
end
local function part1(input)
local floor = 0
for i = 1, #input do
floor = floor + step_delta(input:sub(i, i))
end
return floor
end
return { step_delta = step_delta, part1 = part1 }def step_delta(ch: str) -> int:
if ch == "(":
return 1
if ch == ")":
return -1
return 0
def part1(data: str) -> int:
return sum(step_delta(ch) for ch in data)def step_delta(ch)
case ch
when "(" then 1
when ")" then -1
else 0
end
end
def part1(input)
input.each_char.sum { |ch| step_delta(ch) }
endfn step_delta(ch: char) -> i32 {
match ch {
'(' => 1,
')' => -1,
_ => 0,
}
}
pub fn part1(input: &str) -> i32 {
input.chars().map(step_delta).sum()
}Part 2: First Basement Entry
find the position of the first character that causes him to enter the basement (floor -1).
— Advent of Code 2015, Day 1
Theoretical Explanation
Part 1’s counting shortcut breaks down here: knowing how many ( and ) appear in the string no longer tells you when Santa first dips below ground. Order now matters, so we must watch the running total at every step and catch the smallest index where it hits :
Prefix Sum (Inclusive Scan)
Whereas a fold returns only the final sum, keeping every intermediate total produces a Prefix Sum (or inclusive scan). Kenneth E. Iverson formalized it as the +\ scan operator in APL in 1962, and Guy Blelloch later established it as a fundamental primitive for parallel algorithms (Prefix Sums and Their Applications, 1990).
First-Passage Time & Stopping Time
In probability and combinatorics, is a First-Hitting Time / First-Passage Time—a special case of a Stopping Time, the earliest step at which a path crosses a threshold (here, ). Notice why this matters for performance: the condition depends solely on the symbols seen so far, never on what comes later, so the search can halt the instant it crosses the line.
Online Streaming Optimization
Storing the entire prefix array prefix[1..n] would cost memory, yet each floor depends only on the floor right before it. An Online / Streaming Algorithm discards the history, tracks a single integer floor, and exits immediately once floor == -1.
Complexity Analysis
| Metric | Bound | Notes |
|---|---|---|
| Time (Worst) | Santa enters the basement on the last character, or never. | |
| Time (Best) | The algorithm stops at step 1 if the first character is ). | |
| Space | The algorithm stores no array, only floor and pos. |
Program Steps
- Set
floorto0. - For each character
chat 1-based positionpos = 1, 2, ..., n:- Add
stepDelta(ch)tofloor. - If
floor == -1, returnposimmediately.
- Add
- If the loop ends without hitting
-1, return-1(orNone/nil).
Block Diagram
Implementation
Show Part 2 Implementation10 languages
static int step_delta(char ch) {
if (ch == '(') return 1;
if (ch == ')') return -1;
return 0;
}
int part2(const char *input) {
int floor = 0;
for (int pos = 1; input[pos - 1] != '\0'; pos++) {
floor += step_delta(input[pos - 1]);
if (floor == -1) {
return pos;
}
}
return -1;
}(defn step-delta [ch]
(case ch
\( 1
\) -1
0))
(defn part2 [input]
(->> (map step-delta input)
(reductions + 0)
(map-indexed vector)
(some (fn [[pos floor]] (when (= floor -1) pos)))))package day01
func stepDelta(ch rune) int {
switch ch {
case '(':
return 1
case ')':
return -1
default:
return 0
}
}
func Part2(input string) int {
floor := 0
pos := 0
for _, ch := range input {
pos++
floor += stepDelta(ch)
if floor == -1 {
return pos
}
}
return -1
}module Day01 (stepDelta, part2) where
import Data.List (elemIndex)
stepDelta :: Char -> Int
stepDelta '(' = 1
stepDelta ')' = -1
stepDelta _ = 0
part2 :: String -> Maybe Int
part2 = elemIndex (-1) . scanl (\acc ch -> acc + stepDelta ch) 0public class Day01Part2 {
static int stepDelta(char ch) {
return switch (ch) {
case '(' -> 1;
case ')' -> -1;
default -> 0;
};
}
public static int part2(String input) {
int floor = 0;
for (int i = 0; i < input.length(); i++) {
floor += stepDelta(input.charAt(i));
if (floor == -1) {
return i + 1;
}
}
return -1;
}
}function stepDelta(ch) {
if (ch === '(') return 1;
if (ch === ')') return -1;
return 0;
}
export function part2(input) {
let floor = 0;
let pos = 0;
for (const ch of input) {
pos++;
floor += stepDelta(ch);
if (floor === -1) {
return pos;
}
}
return -1;
}local function step_delta(ch)
if ch == "(" then
return 1
elseif ch == ")" then
return -1
end
return 0
end
local function part2(input)
local floor = 0
for pos = 1, #input do
floor = floor + step_delta(input:sub(pos, pos))
if floor == -1 then
return pos
end
end
return nil
end
return { step_delta = step_delta, part2 = part2 }def step_delta(ch: str) -> int:
if ch == "(":
return 1
if ch == ")":
return -1
return 0
def part2(data: str) -> int | None:
floor = 0
for pos, ch in enumerate(data, start=1):
floor += step_delta(ch)
if floor == -1:
return pos
return Nonedef step_delta(ch)
case ch
when "(" then 1
when ")" then -1
else 0
end
end
def part2(input)
floor = 0
input.each_char.with_index(1) do |ch, pos|
floor += step_delta(ch)
return pos if floor == -1
end
nil
endfn step_delta(ch: char) -> i32 {
match ch {
'(' => 1,
')' => -1,
_ => 0,
}
}
pub fn part2(input: &str) -> Option<usize> {
let mut floor = 0;
for (idx, ch) in input.chars().enumerate() {
floor += step_delta(ch);
if floor == -1 {
return Some(idx + 1);
}
}
None
}