donnemartin/interactive-coding-challenges · error · TypeError

str1 or str2 cannot be None

Error message

str1 or str2 cannot be None

What it means

Raised by Solution.find_diff when str1 or str2 is None. The algorithm counts characters across both strings to find the extra char, so both must be actual strings. The guard fails fast with TypeError instead of a confusing iteration error.

Source

Thrown at arrays_strings/str_diff/str_diff_solution.ipynb:103

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "\n",
    "    def find_diff(self, str1, str2):\n",
    "        if str1 is None or str2 is None:\n",
    "            raise TypeError('str1 or str2 cannot be None')\n",
    "        seen = {}\n",
    "        for char in str1:\n",
    "            if char in seen:\n",
    "                seen[char] += 1\n",
    "            else:\n",
    "                seen[char] = 1\n",
    "        for char in str2:\n",
    "            try:\n",
    "                seen[char] -= 1\n",
    "            except KeyError:\n",
    "                return char\n",
    "            if seen[char] < 0:\n",
    "                return char\n",
    "        for char, count in seen.items():\n",
    "            return char\n",
    "\n",
    "    def find_diff_xor(self, str1, str2):\n",
    "        if str1 is None or str2 is None:\n",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Coerce to empty string when None: find_diff(s1 or '', s2 or '') if empty-vs-full is meaningful for you
  2. Validate both inputs are str at the request boundary
  3. Skip the diff entirely when either side is missing

Example fix

# before
Solution().find_diff(old, new)  # old may be None

# after
if old is not None and new is not None:
    Solution().find_diff(old, new)
Defensive patterns

Strategy: validation

Validate before calling

if str1 is not None and str2 is not None:
    Solution().find_diff(str1, str2)

Type guard

def is_diffable(s) -> bool:
    return isinstance(s, str)

Try / catch

try:
    Solution().find_diff(str1, str2)
except TypeError:
    return None  # missing input, no diff

Prevention

When it happens

Trigger: Calling find_diff(None, s) or find_diff(s, None); passing values from optional fields or unvalidated input.

Common situations: Comparing user-supplied strings where one side is optional; diffing file contents when one read returned None; API params forwarded without validation.

Related errors


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