Skip to the code
cf.
+50 XP

#621 How Often Each Prefix Appears

hard

An autocomplete service wants to know, for a popular query, how often each of its prefixes appears inside the query itself, to tune suggestions.

Write prefixCounts(query) that returns an array counts of length n, where counts[L - 1] is the number of positions where query.slice(0, L) occurs in query (overlaps allowed). The prefix itself at position 0 counts, so every entry is at least 1.

Queries can be 100,000 characters long; checking each prefix separately is too slow.

Example 1

Input: query = "abab"
Output: [2,2,1,1]

a and ab each appear twice; aba and abab once.

Example 2

Input: query = "aaa"
Output: [3,2,1]

a three times, aa twice, aaa once.

Constraints

  • 1 <= query.length <= 10^5
  • query contains lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).