TheAlgorithms/JavaScript · error · TypeError
Invalid Input Type
Error message
Invalid Input Type
What it means
Guard in lengthOfLongestSubstring. The function computes the length of the longest substring without repeating characters using a sliding window + Map, and requires the input to be a string, throwing TypeError otherwise.
Source
Thrown at String/LengthofLongestSubstringWithoutRepetition.js:12
/*
* @description : Given a string, the function finds the length of the longest substring without any repeating characters
* @param {String} str - The input string
* @returns {Number} The Length of the longest substring in a given string without repeating characters
* @example lengthOfLongestSubstring("abcabcbb") => 3
* @example lengthOfLongestSubstring("bbbbb") => 1
* @see https://leetcode.com/problems/longest-substring-without-repeating-characters/
*/
const lengthOfLongestSubstring = (s) => {
if (typeof s !== 'string') {
throw new TypeError('Invalid Input Type')
}
let maxLength = 0
let start = 0
const charMap = new Map()
for (let end = 0; end < s.length; end++) {
if (charMap.has(s[end])) {
start = Math.max(start, charMap.get(s[end]) + 1)
}
charMap.set(s[end], end)
maxLength = Math.max(maxLength, end - start + 1)
}
return maxLength
}
export { lengthOfLongestSubstring }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string; coerce numbers via String(n).
- Default missing values to '' (returns 0).
- Validate typeof at the boundary.
Example fix
// before lengthOfLongestSubstring(maybeStr) // after lengthOfLongestSubstring(typeof maybeStr === 'string' ? maybeStr : String(maybeStr ?? ''))
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof s !== 'string') {
throw new TypeError('s must be a string')
}
lengthOfLongestSubstring(s) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
lengthOfLongestSubstring(input)
} catch (e) {
if (e instanceof TypeError && /Invalid Input Type/i.test(e.message)) { /* not a string */ } else throw e
} Prevention
- Coerce numbers via String().
- Default missing values to '' (returns 0).
- Validate typeof at the boundary.
When it happens
Trigger: Calling lengthOfLongestSubstring(undefined), lengthOfLongestSubstring(null), lengthOfLongestSubstring(12345), lengthOfLongestSubstring(['a','b','c']). Any input where typeof !== 'string'.
Common situations: A LeetCode input arriving as a number; a payload field that is null; passing an array of characters instead of a string.
Related errors
- Argument should be string
- Argument is not a string.
- Argument is not a string.
- The first param should be a string
- The second param should be a boolean
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/fad26b39a2d5a061.
Report an issue: GitHub.