DSA Tracker

Medium

Count Distinct Substrings Using Trie

A medium Trie problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Trie
Sheets
1
Core for
7 roles
Platform
GeeksforGeeks

The problem

Given a string, count the total number of distinct non-empty substrings that can be formed from it.

Example 1

Input
s = "ababa"
Output
9
Why
The distinct substrings are: 'a', 'ab', 'aba', 'abab', 'ababa', 'b', 'ba', 'bab', 'baba'.

Example 2

Input
s = "abc"
Output
6
Why
The distinct substrings are: 'a', 'ab', 'abc', 'b', 'bc', 'c'.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters

How to think about it

Updated 2026-09-09

Every substring of a string is a prefix of some suffix. Inserting all suffixes of the string into a trie maps every distinct substring to exactly one node in the tree. The total count of distinct non-empty substrings is therefore the total count of newly created nodes across all suffix insertions.

Approaches, worst first

  1. Hash set of substrings

    time O(n^3) · space O(n^3)

    Extract all O(n^2) substrings using two nested loops and insert each into a hash set. Returning the set size gives the answer, but copying and hashing O(n^2) strings of average length O(n) consumes quadratic time and cubic memory.

  2. Suffix trie node countingWrite this one

    time O(n^2) · space O(n^2 * 26)

    For each starting index i from 0 to n - 1, traverse down the trie inserting characters s[j] from i to n - 1. Increment a global counter whenever a new child node is instantiated, eliminating string slicing and hashing overhead entirely.

Where people lose marks · 2
  • Materializing string slices inside the nested loop instead of streaming characters into the trie, triggering large memory allocations in garbage-collected runtimes.
  • Forgetting that the problem asks for non-empty substrings; counting the trie root node would overestimate the total count by one.

The theory behind it

Trie — the ground this problem stands on. All Trie problems

What Trie is

A trie, also called a prefix tree, is a tree structured for storing words character by character. Instead of storing entire words in individual nodes, each step down a branch represents a single letter. Words that share the same beginning, like car, card, and care, share the exact same starting path down the tree. A special boolean marker sits at the end of each valid word to show that a complete word terminates at that letter.

When to reach for it

Reach for a trie when questions involve prefix lookups, dictionary word searches, autocomplete engines, or matching prefixes against a body of text. Prompts asking whether any word in a dictionary begins with a given prefix, or searching for words on a Boggle board grid, point directly to a trie. It also applies to bitwise tasks, such as finding the maximum XOR pair among integers by treating numbers as binary prefixes.

How the pattern works

Represent each trie node with an array or hash map of child links, plus a boolean flag marking if a complete word ends at that node. When inserting, start at the root and walk down character by character, creating new child nodes whenever a path does not exist yet, then mark the final node as a word ending. When searching, follow the characters; if any child link is missing, the word or prefix does not exist. If all characters match, check the boolean flag to distinguish between a full word and a partial prefix.

What each operation costs

OperationTime
insert word of length l into trieO(l)
search for full word of length lO(l)
check if any word begins with prefix of length lO(l)
What usually goes wrong with Trie
  • Confusing prefix matches with full word matches by returning true when characters exist but the end-of-word flag on the final node was never set.
  • Allocating fixed 26-slot arrays for child pointers without verifying that all input characters are strictly lowercase English letters.
  • Forgetting to prune unvisited branches during board searches, leading to time limit exceeded errors on grids with large word sets.

Which roles need this problem

Trie is a core topic for these 7 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 2 more roles, including Information Retrieval Engineer, Storage Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Trie problems

Problem set and role mapping as of .