File: valid-word-abbreviation/solution.py

Date: 2026-06-06

Time: 19:40

Purpose

This file implements LeetCode problem 408 - Valid Word Abbreviation. It determines whether a given abbreviation string is a valid representation of a word, where digits in the abbreviation represent the count of characters they replace. For example, "i12iz4n" is a valid abbreviation of "internationalization" because i + 12 skipped chars + iz + 4 skipped chars + n reconstructs the full word.

The file is self-contained: it defines the solution function and its unit tests in one module, following the repo-wide convention of colocating implementation and tests.

Key Components

validWordAbbreviation(word, abbr) -> bool

The sole public function. It walks both strings in lockstep using a two-pointer approach:

When abbr[j] is a letter, it must match word[i] exactly. When abbr[j] is a digit, the function parses the full multi-digit number and advances i by that amount (skipping that many characters in word).

The function returns True only when both pointers reach the end of their respective strings simultaneously.

TestValidWordAbbreviation

16 test cases covering:

Patterns

Two-pointer string matching — the canonical approach for this problem. One pointer per input string, advanced at different rates depending on whether the current abbreviation character is a letter or digit.

Digit accumulation via Horner's methodnum = num * 10 + int(abbr[j]) builds multi-digit numbers one character at a time without slicing or int() on a substring.

Self-contained module — solution + tests in one file, runnable via python -m unittest or python solution.py. This is the standard layout across the entire repo.

Dependencies

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

Imported by: The testsolution.py file in the same directory. The massive "Imported By" list in the prompt is misleading — those are other problems' test files that import unittest, not this module. Only valid-word-abbreviation/testsolution.py actually imports from this file.

Flow

1. Initialize i = 0 (word pointer), j = 0 (abbr pointer).

2. Loop while both pointers are in bounds:

3. Return i == len(word) and j == len(abbr) — both must be fully consumed.

Invariants

Error Handling

There is none beyond returning False for invalid inputs. The function assumes both inputs are well-formed strings (lowercase letters for word, lowercase letters and digits for abbr). Out-of-bounds access is prevented by the loop guard i < len(word) and j < len(abbr), and the digit-parsing inner loop checks j < len(abbr).

Topics to Explore

Beliefs