DSA interview question
You're building a search-suggestion/autocomplete indexing engine. To estimate how rich the indexable content is for a given document, your team wants a metric: the total number of distinct substrings in a string. This becomes the basis for a more advanced "substring diversity score" feature. Given a string s, return the count of all distinct (non-empty) substrings.
Example: s = "ababa" → there are 9 distinct substrings: "a", "b", "ab", "ba", "aba", "bab", "abab", "baba", "ababa".
int countDistinctSubstrings(string s);
Input s | Output | Explanation |
|---|---|---|
"ababa" | 9 | Listed above — note total possible substrings would be 5*6/2=15, but duplicates reduce it to 9 |
"aaaa" | 4 | Only "a", "aa", "aaa", "aaaa" — all repeats of the same character collapse to 4 distinct entries |
"abc" | 6 | All substrings unique: "a","b","c","ab","bc","abc" |
"a" | 1 | Just "a" |
"" | 0 | Empty string has no substrings |
"aaa" | 3 | "a","aa","aaa" |
"abab" | 7 | "a","b","ab","ba","aba","bab","abab" (note: "ab" appears twice as a substring occurrence, counted once) |
s? (Critical — naive approaches are O(n³) or O(n² log n); for large n (like 10⁴–10⁵), you need O(n²) Trie or O(n log n) suffix array/automaton approaches.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in