00:00

Problem Statement

Input/Output Examples

Visual Explanation

Resuming at match + sub.length() is what prevents overlap. Resuming at match + 1 instead would also find the overlapping match at index 3 and return 2.

Approaches

Both approaches skip past each match. The first relies on indexOf(); the second tests each position with startsWith().

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the text and m is the length of the substring. Each position may need up to m character comparisons; KMP would reduce this to O(n + m).

Interview Tips and Recommended Approach

  • Clarify overlap first. For "aaaa" and "aa", the answer is 2 without overlap and 3 with it.
  • Guard against an empty substring. indexOf("") matches at every position, so the loop would never end.
  • Avoid the split trick. text.split(sub).length - 1 fails when the match is at the end and treats sub as a regex.
  • Know the regex alternative: Pattern.compile(Pattern.quote(sub)).matcher(text) with a find() loop also counts non-overlapping matches.

Recommended Approach: indexOf() Loop

Why: it uses the JDK's optimised search, makes the non-overlap rule a single expression and needs no extra memory.