donnemartin/interactive-coding-challenges · error · TypeError
k must be of type int
Error message
k must be of type int
What it means
Raised by Solution.longest_substr when k is not an int (including None). It is the second guard, after the string check, because the algorithm compares len(chars_to_index_map) > k numerically; a non-int k would make that comparison meaningless or raise elsewhere.
Source
Thrown at recursion_dynamic/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 not isinstance(string, str):\n",
" raise TypeError('string must be of type str')\n",
" if not isinstance(k, int):\n",
" raise TypeError('k must be of type int')\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
- Convert at the boundary: k = int(k) for str/float inputs
- Provide a concrete default: def longest_substr(string, k=1) at your own wrapper
- Validate k is int (and >= 0) before calling
Example fix
// before
sol.longest_substr(s, k=request.args.get('k'))
// after
sol.longest_substr(s, k=int(request.args.get('k', 2))) Defensive patterns
Strategy: validation
Validate before calling
k = int(k) if k is not None else 1 sol.longest_substr(string, k)
Type guard
def is_int(x):
return isinstance(x, int) and not isinstance(x, bool) Try / catch
try:
sol.longest_substr(string, k)
except TypeError:
k = int(k)
n = sol.longest_substr(string, k) Prevention
- Cast CLI/query params to int immediately
- Set explicit defaults for k
When it happens
Trigger: Calling longest_substr('abc', None), longest_substr('abc', '2'), or longest_substr('abc', 2.0). Note bool is a subclass of int and would pass this check.
Common situations: Taking k from CLI args or query strings where it arrives as str; k read from JSON config as float; forgotten default leaving k=None.
Understand the failure class
Background: "Wrong argument type", "must be a string", "expected Array or Prism::Scope": TypeError and ArgumentError when a library receives a value of the wrong type — this error's family across 28 libraries.
Related errors
- string must be of type str
- string cannot be None
- k cannot be None
- num cannot be None
- max_num cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/2f9bc4efb46158fa.
Report an issue: GitHub.