File: first-letter-to-appear-twice/solution.py

Date: 2026-06-06

Time: 16:50

Purpose

This file solves LeetCode 2351: First Letter to Appear Twice. It owns the core algorithm for the problem: given a string of lowercase letters where at least one letter repeats, find the first letter whose second occurrence appears earliest (i.e., has the smallest index for its second appearance).

Key Components

firstlettertoappeartwice(s: str) -> str

The sole export. Contract:

Patterns

Set-based membership tracking. The function uses the classic "seen set" idiom — iterate through elements, check membership in O(1), add if new, return on first collision. This is the textbook approach for "first duplicate in a stream" problems.

Early return. The function exits as soon as it finds the answer, avoiding unnecessary iteration over the rest of the string. There is no post-loop fallback — the problem guarantees a duplicate exists, so the loop always terminates via return.

Dependencies

Imports: None. Uses only Python builtins (set).

Imported by: The "Imported By" list in the prompt is misleading — it lists ~400+ test files across unrelated problems. This is likely an artifact of a shared test runner or import framework, not genuine cross-problem dependencies. The actual consumer is first-letter-to-appear-twice/test_solution.py.

Flow

1. Initialize empty set called seen.

2. Iterate character-by-character through s.

3. For each character c:

4. Implicit: function has no explicit return None — it relies on the problem's guarantee that a duplicate exists.

Time complexity: O(n) worst case, but bounded by O(26) since there are only 26 lowercase letters — the pigeonhole principle guarantees a collision by the 27th character.

Space complexity: O(1) — the set holds at most 26 entries.

Invariants

Error Handling

None. The function trusts its caller to satisfy the precondition (at least one repeated letter). If the precondition is violated, the function returns None implicitly — no exception, no sentinel value. This is acceptable for a LeetCode solution where inputs are constrained by the problem statement.

Topics to Explore

Beliefs