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

  1. Pass a string; coerce numbers via String(n).
  2. Default missing values to '' (returns 0).
  3. 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

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


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/fad26b39a2d5a061. Report an issue: GitHub.