TheAlgorithms/Python · error · ValueError

longest_common_substring() takes two strings for inputs

Error message

longest_common_substring() takes two strings for inputs

What it means

Raised by longest_common_substring(text1, text2) when either argument fails isinstance(x, str). The DP algorithm indexes characters of both inputs, so non-string arguments (ints, lists, None) are rejected up front with this ValueError. Empty strings are valid and return '' via the following check, not this error.

Source

Thrown at dynamic_programming/longest_common_substring.py:44

    'bcd'
    >>> longest_common_substring("abcdef", "xabded")
    'ab'
    >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz")
    'Geeks'
    >>> longest_common_substring("abcdxyz", "xyzabcd")
    'abcd'
    >>> longest_common_substring("zxabcdezy", "yzabcdezx")
    'abcdez'
    >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com")
    'Site:Geeks'
    >>> longest_common_substring(1, 1)
    Traceback (most recent call last):
        ...
    ValueError: longest_common_substring() takes two strings for inputs
    """

    if not (isinstance(text1, str) and isinstance(text2, str)):
        raise ValueError("longest_common_substring() takes two strings for inputs")

    if not text1 or not text2:
        return ""

    text1_length = len(text1)
    text2_length = len(text2)

    dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)]
    end_pos = 0
    max_length = 0

    for i in range(1, text1_length + 1):
        for j in range(1, text2_length + 1):
            if text1[i - 1] == text2[j - 1]:
                dp[i][j] = 1 + dp[i - 1][j - 1]
                if dp[i][j] > max_length:
                    end_pos = i
                    max_length = dp[i][j]

View on GitHub (pinned to f5988cc097)

Solutions

  1. Decode bytes before calling: longest_common_substring(a.decode(), b.decode()).
  2. Coerce or default missing inputs: text1 = text1 or ''.
  3. Join char lists: ''.join(chars) before the call.

Example fix

# before
lcs = longest_common_substring(payload_a, payload_b)  # bytes -> ValueError

# after
lcs = longest_common_substring(payload_a.decode('utf-8'), payload_b.decode('utf-8'))
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(text1, str):
    text1 = text1.decode() if isinstance(text1, bytes) else str(text1)
if not isinstance(text2, str):
    text2 = text2.decode() if isinstance(text2, bytes) else str(text2)
result = longest_common_substring(text1, text2)

Type guard

def is_str_pair(a: object, b: object) -> bool:
    return isinstance(a, str) and isinstance(b, str)

Try / catch

try:
    result = longest_common_substring(text1, text2)
except ValueError as exc:
    if 'two strings' in str(exc):
        raise TypeError('both inputs must be str; decode bytes first') from exc
    raise

Prevention

When it happens

Trigger: longest_common_substring(1, 1) as in the doctest; passing bytes (b'abc') since bytes is not str; passing None when one input is missing; passing a list of characters instead of a joined string.

Common situations: Data read as bytes from files/networks in Python 3; optional fields that default to None; iterating characters into a list instead of using the string directly.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/d0943efd1d3a6687. Report an issue: GitHub.