donnemartin/interactive-coding-challenges · error · TypeError
nums or target cannot be None
Error message
nums or target cannot be None
What it means
Raised by Solution.two_sum when nums or target is None. The method caches complements while scanning nums, so both must be valid; None is rejected with TypeError before any logic runs. Note the separate ValueError for empty nums lists.
Source
Thrown at arrays_strings/two_sum/two_sum_solution.ipynb:166
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def two_sum(self, nums, target):\n",
" if nums is None or target is None:\n",
" raise TypeError('nums or target cannot be None')\n",
" if not nums:\n",
" raise ValueError('nums cannot be empty')\n",
" cache = {}\n",
" for index, num in enumerate(nums):\n",
" cache_target = target - num\n",
" if num in cache:\n",
" return [cache[num], index]\n",
" else:\n",
" cache[cache_target] = index\n",
" return None"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]View on GitHub (pinned to 358f2cc604)
Solutions
- Validate both parameters at the call boundary before invoking two_sum
- Return an explicit error/empty result to the caller when either is missing
- Fix the producer so target is always computed (e.g. not data.get('target'))
Example fix
# before
Solution().two_sum(nums, params.get('target'))
# after
target = params.get('target')
if nums is not None and target is not None:
result = Solution().two_sum(nums, target) Defensive patterns
Strategy: validation
Validate before calling
if nums is not None and target is not None:
Solution().two_sum(nums, target) Type guard
def valid_two_sum_input(nums, target) -> bool:
return nums is not None and target is not None Try / catch
try:
Solution().two_sum(nums, target)
except TypeError:
return [] # or surface a validation error Prevention
- Validate API params before algorithm calls
- Distinguish TypeError (None input) from ValueError (empty list) in handlers
When it happens
Trigger: Calling two_sum(None, 9) or two_sum([2,7], None); forwarding unset request parameters.
Common situations: API handlers passing optional nums/target params unvalidated; data pipelines where the array or target comes from an optional field.
Related errors
- data cannot be None
- str1 or str2 cannot be None
- neighbor or weight cannot be None
- neighbor cannot be None
- key cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/b0239e0d1315f8a7.
Report an issue: GitHub.