Day 1:Not Quite Lisp

Monoid reductions, prefix sums, and first-passage times on a 1D lattice path.

Time: O(n)Space: O(1)EasyFold / ReductionPrefix Sum (Scan)Streaming AlgorithmPuzzle Prompt ↗

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 by 1.
  • ) moves the counter down by 1.

Written formally, the input is a finite string s=s1s2…sns = s_1 s_2 \dots s_n over the two-symbol alphabet Σ={’(’,’)’}\Sigma = \{\text{'('}, \text{')'}\}, and each symbol maps to a step through a helper function δ:Σ→{−1,+1}\delta : \Sigma \to \{-1, +1\}:

δ(c)={+1if c=’(’−1if c=’)’\delta(c) = \begin{cases} +1 & \text{if } c = \text{'('} \\ -1 & \text{if } c = \text{')'} \end{cases}

Starting from ground floor F0=0F_0 = 0, the floor after kk instructions is the kk-th partial sum:

Fk=∑i=1kδ(si)F_k = \sum_{i=1}^{k} \delta(s_i)

Plot those floors (F0,F1,…,Fn)(F_0, F_1, \dots, F_n) 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 00, ends at 00, and never dips below ground, mathematicians call it a Dyck path, named after Walther von Dyck.

Isolating δ(c)\delta(c) 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 Fn=∑i=1nδ(si)F_n = \sum_{i=1}^{n} \delta(s_i) 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 (Z,+,0)(\mathbb{Z}, +, 0) form a commutative monoid: addition is associative, has an identity element (00), and ignores order. As a result, FF is a monoid homomorphism from strings (Σ∗,⋅,ε)(\Sigma^*, \cdot, \varepsilon) to (Z,+,0)(\mathbb{Z}, +, 0):

F(u⋅v)=F(u)+F(v),F(ε)=0F(u \cdot v) = F(u) + F(v), \qquad F(\varepsilon) = 0

That algebraic symmetry buys two practical payoffs:

  1. Order Independence & Parallelism: Since you can regroup and reorder additions freely, pp threads can sum separate chunks of the string and merge their totals in O(n/p+log⁡p)O(n/p + \log p) parallel time (Parallel Reduction).
  2. Counting Identity: When the input contains only ( and ), the final floor simplifies to Fn=c’(’−c’)’=2⋅c’(’−nF_n = c_{\text{'('}} - c_{\text{')'}} = 2 \cdot c_{\text{'('}} - n, 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 FnF_n by ±2\pm 2 and forcing a wrong answer. Every sequential algorithm therefore needs at least Ω(n)\Omega(n) time, which makes our O(n)O(n) time, O(1)O(1) space fold optimal.

Complexity Analysis

MetricBoundNotes
TimeO(n)O(n)Tight Θ(n)\Theta(n). The algorithm must read every character.
SpaceO(1)O(1)The algorithm stores one integer, floor.

Program Steps

  1. Set floor to 0.
  2. For each character ch in input:
    1. Calculate d = stepDelta(ch) (+1 for '(', -1 for ')', 0 otherwise).
    2. Add d to floor.
  3. Return floor.

Block Diagram

Initializefloor = 0Next characterch in inputAccumulatefloor += delta(ch)more charactersEOFReturnfloor
Part 1: Streaming reduction (fold) over the instruction string.

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;
}

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 k≥1k \ge 1 where it hits −1-1:

k∗=min⁡{k∈{1,…,n}∣Fk=−1}k^* = \min \{ k \in \{1, \dots, n\} \mid F_k = -1 \}

Prefix Sum (Inclusive Scan)

Whereas a fold returns only the final sum, keeping every intermediate total (F1,F2,…,Fn)(F_1, F_2, \dots, F_n) 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, k∗k^* 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, −1-1). Notice why this matters for performance: the condition {Fk=−1}\{F_k = -1\} 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 O(n)O(n) memory, yet each floor Fk=Fk−1+δ(sk)F_k = F_{k-1} + \delta(s_k) 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

MetricBoundNotes
Time (Worst)O(n)O(n)Santa enters the basement on the last character, or never.
Time (Best)Ω(1)\Omega(1)The algorithm stops at step 1 if the first character is ).
SpaceO(1)O(1)The algorithm stores no array, only floor and pos.

Program Steps

  1. Set floor to 0.
  2. For each character ch at 1-based position pos = 1, 2, ..., n:
    1. Add stepDelta(ch) to floor.
    2. If floor == -1, return pos immediately.
  3. If the loop ends without hitting -1, return -1 (or None / nil).

Block Diagram

Initializefloor=0, pos=1Update Prefix Sumfloor += delta(s[pos])floor == -1?stopping cond.yesReturn posearly exitnoAdvancepos = pos + 1if pos > n, return not found
Part 2: Online prefix scan with early termination at the first-passage barrier (floor == -1).

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;
}