donnemartin/interactive-coding-challenges · error · TypeError

string cannot be None

Error message

string cannot be None

What it means

Raised by Solution.longest_substr (longest substring with at most k distinct chars) when string is None. The method enumerates the string; None would fail inside the loop, so the guard requires a str at the API boundary.

Source

Thrown at online_judges/longest_substr_k_distinct/longest_substr_solution.ipynb:102

  },
  {
   "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": {},

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass a string (empty string '' is fine and returns 0)
  2. Default at the call site: s = s or ''
  3. Fix the producer returning None for missing text

Example fix

# before
solution.longest_substr(payload.get('text'), k)  # text field may be null

# after
solution.longest_substr(payload.get('text') or '', k)
Defensive patterns

Strategy: validation

Validate before calling

string = string or ''
solution.longest_substr(string, k)

Type guard

def is_str(s): return isinstance(s, str)

Try / catch

try:
    n = solution.longest_substr(s, k)
except TypeError:
    n = 0

Prevention

When it happens

Trigger: Calling longest_substr(None, 2) — an unset variable, a None default parameter, or text fetched from a nullable field/API response.

Common situations: Processing nullable text fields from JSON payloads; tests asserting the guard; optional CLI args passed through unvalidated.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/370ee4cdf115fb07. Report an issue: GitHub.