File: find-smallest-letter-greater-than-target/solution.py

Date: 2026-06-06

Time: 16:42

Purpose

This file is the solution and test suite for LeetCode 744 — Find Smallest Letter Greater Than Target. It owns the complete implementation: the algorithm in Solution.nextGreatestLetter and nine unit tests covering edge cases. Like every other problem directory in this repo, it follows the convention of bundling solution + tests in a single solution.py.

Key Components

Solution.nextGreatestLetter(letters, target) -> str

The core algorithm. Given a sorted list of lowercase letters and a target character, returns the smallest letter strictly greater than the target. If no such letter exists (target >= all letters), it wraps around and returns the first letter in the list.

The entire implementation is two lines:


idx = bisect_right(letters, target)
return letters[idx % len(letters)]

bisect_right returns the insertion point *after* any existing copies of target, which is exactly the index of the first element strictly greater than target. The modulo handles the wrap-around: when idx == len(letters) (target >= everything), idx % len(letters) evaluates to 0, returning letters[0].

TestNextGreatestLetter

Nine test methods covering:

Patterns

Dependencies

Imports:

Imported by: The testsolution.py files listed in the "Imported By" section are other problems' test files — this is likely an artifact of the static analysis tool rather than a real import relationship. The actual reverse dependency is find-smallest-letter-greater-than-target/testsolution.py, which imports and runs the tests from this file.

Flow

1. bisect_right(letters, target) performs O(log n) binary search, returning the index where target would be inserted to keep letters sorted, placed *after* any existing copies of target.

2. The modulo maps the index into [0, len(letters)), handling the wrap-around case.

3. letters[idx % len(letters)] returns the answer in O(1).

Total: O(log n) time, O(1) space.

Invariants

Error Handling

None — the function trusts its inputs match the LeetCode contract. No validation, no exceptions. This is appropriate for a competitive-programming solution where inputs are guaranteed valid.