Find the bug · Easy

Fix the Substring Check

Easy Find the bug Most asked

containsWord(text, word) returns true when word occurs anywhere in text (case-sensitive), and false otherwise.

A user reports that searching for "Error" in "Error: disk full" returns false. Find the bug and fix it. The same bug exists in every language version.

Example 1

Input: text = "disk full: Error", word = "Error"
Output: true

Example 2

Input: text = "Error: disk full", word = "Error"
Output: true
Explanation: The buggy version returns false.

The buggy code

function containsWord(text, word) {
  if (text.indexOf(word)) return true;
  return false;
}

Hints

Hint 1

What does indexOf / strpos / find return when the match starts at position 0?

Hint 2

And what do they return when there is no match at all?

Find and fix the bug

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the bug and the fix

Time O(n x m) · Space O(1)

The bug: the position of the match is used as a boolean. A match at position 0 is falsy, so it reads as "not found". In JavaScript and Python the no-match value (-1) is truthy, so the check is also backwards for missing words; in PHP, strpos returns false for no match and 0 for a match at the start, and both look false to if. Java's version compares > 0, which has the same off-by-one.

The fix: use the API that returns a boolean (includes, in, str_contains, contains), or compare explicitly against the not-found value (!== -1, !== false, >= 0).

This is one of the most common PHP interview gotchas, and the PHP manual has a warning box about it on the strpos page.

Fixed version

function containsWord(text, word) {
  return text.includes(word); // or: text.indexOf(word) !== -1
}

Common mistakes

  • PHP: if (strpos(...) != false) with loose comparison: 0 == false is true, so it is still wrong.