File: single-row-keyboard/solution.py

Date: 2026-06-06

Time: 19:07

Purpose

This file solves LeetCode 1165 - Single Row Keyboard. It calculates the total time to type a word on a keyboard where all 26 letters are arranged in a single row. The "time" to move between keys equals the absolute difference of their positions. The finger starts at position 0 (the first key).

Key Components

calculate_time(keyboard: str, word: str) -> int

The sole public function. Contract:

TestCalculateTime

Seven unit tests covering:

Patterns

Precomputed index map: The function builds a pos dictionary mapping each character to its keyboard index in O(26) time before iterating the word. This is the standard hash-map-for-O(1)-lookup idiom — avoids calling keyboard.index(c) (O(26)) per character.

Accumulator loop: Tracks current position and accumulates total cost in a single pass over word. This is the canonical "simulate the process" pattern for position-tracking problems.

Self-contained test file: Tests live alongside the solution rather than in a separate test directory, following the project-wide convention visible in the repository structure.

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — it lists hundreds of test files across the entire repo. This is likely an artifact of the analysis tool picking up import unittest as a shared dependency, not actual imports of this module's calculatetime function. The real consumer is single-row-keyboard/testsolution.py.

Flow

1. Build pos: {c: i for i, c in enumerate(keyboard)} — O(26) dictionary comprehension.

2. Initialize current = 0 (finger starts at the leftmost key).

3. For each character c in word:

4. Return total.

Total complexity: O(n) where n = len(word), with O(1) space beyond the fixed-size 26-entry dictionary.

Invariants

Error Handling

None. Invalid inputs (characters not in the keyboard, empty keyboard, non-lowercase characters) will raise unhandled KeyError or produce silently wrong results. This is typical for LeetCode solutions where inputs are guaranteed valid by the problem constraints.

Topics to Explore

Beliefs