Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1698: Number of Distinct Substrings in a String

In this guide, we solve Leetcode #1698 Number of Distinct Substrings in a String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a string s, return the number of distinct substrings of s. A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Trie, String, Suffix Array, Hash Function, Rolling Hash

Intuition

Prefix queries are most efficient with a trie.

Each character transitions to the next node in the tree.

Approach

Insert words into the trie and traverse by characters for queries.

Track terminal markers to distinguish full words from prefixes.

Steps:

  • Build the trie.
  • Traverse for each query.
  • Return matches or validations.

Example

Input: s = "aabbaba" Output: 21 Explanation: The set of distinct strings is ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]

Python Solution

class Solution: def countDistinct(self, s: str) -> int: n = len(s) return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)})

Complexity

The time complexity is O(n3)O(n^3)O(n3), and the space complexity is O(n2)O(n^2)O(n2). The space complexity is O(n2)O(n^2)O(n2).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy