Skip to the code
+50 XP

#632 Count Distinct Snippets

hard

An autocomplete service estimates how big a substring index for a text would be by counting its distinct non-empty substrings. Equal substrings at different positions count once.

Write countDistinct(text) that returns that number. Texts can be up to 100,000 characters, so making every substring is far too slow and needs far too much memory.

Example 1

Input: text = "aba"
Output: 5

a, b, ab, ba, aba; the second a is a repeat.

Example 2

Input: text = "aaa"
Output: 3

Only a, aa, and aaa.

Constraints

  • 0 <= text.length <= 10^5
  • text contains lowercase letters.
  • The answer fits in a JavaScript number.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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