donnemartin/interactive-coding-challenges · error · TypeError
k cannot be None
Error message
k cannot be None
What it means
Raised by Solution.longest_substr when k is None. k is compared as len(chars_to_index_map) > k; None would break that comparison, so the method requires an integer k (the max number of distinct characters) explicitly.
Source
Thrown at online_judges/longest_substr_k_distinct/longest_substr_solution.ipynb:104
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def longest_substr(self, string, k):\n",
" if string is None:\n",
" raise TypeError('string cannot be None')\n",
" if k is None:\n",
" raise TypeError('k cannot be None')\n",
" low_index = 0\n",
" max_length = 0\n",
" chars_to_index_map = {}\n",
" for index, char in enumerate(string):\n",
" chars_to_index_map[char] = index\n",
" if len(chars_to_index_map) > k:\n",
" low_index = min(chars_to_index_map.values())\n",
" del chars_to_index_map[string[low_index]]\n",
" low_index += 1\n",
" max_length = max(max_length, index - low_index + 1)\n",
" return max_length"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"View on GitHub (pinned to 358f2cc604)
Solutions
- Pass an integer k, e.g. longest_substr('eceba', 2)
- Default at the call site: k = 2 if k is None else k
- Validate config/argv before the call and fail with a clear message
Example fix
# before
solution.longest_substr(s, config.get('k'))
# after
k = config.get('k')
if k is None:
raise ValueError('k is required')
solution.longest_substr(s, int(k)) Defensive patterns
Strategy: validation
Validate before calling
if k is None: raise ValueError('k is required')
solution.longest_substr(string, int(k)) Type guard
def is_int(x): return isinstance(x, int)
Try / catch
try:
n = solution.longest_substr(s, k)
except TypeError:
n = solution.longest_substr(s, DEFAULT_K) Prevention
- Set explicit defaults for k in CLI/config parsing
- Cast and validate numeric params once at entry
When it happens
Trigger: Calling longest_substr('abc', None) — usually a k read from argv/config that was never set, or an optional parameter defaulting to None.
Common situations: CLI parsing where k = args.k with no default; config-driven workloads with a missing key; tests asserting the guard.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/2e219599b38081a0.
Report an issue: GitHub.