MEDIUM 1-D Dynamic Programming

946. Distinct Substrings (LeetCode 1698)

šŸ“– Problem

Given a string s, return the number of distinct substrings of s. A string substring is a contiguous sequence of characters within the string.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •Array DP table updates
  • •State transition thinking
  • •Base case initialization

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Dynamic Programming reasoning pattern

šŸ’” Approach

  • → Use DP where dp[i] represents number of distinct substrings ending at position i
  • → For each position, consider all possible endings of substrings
  • → Use hash set to track seen substrings
  • → Time: O(n²), Space: O(n²)
  • → Alternative approach: Use suffix automaton or suffix array for O(n) solution

šŸ› ļø Hints & Pitfalls

Hints

  • •Use DP where dp[i] represents number of distinct substrings ending at position i
  • •For each position, consider all possible endings of substrings
  • •Use hash set to track seen substrings

Common Pitfalls

  • •Time: O(n²), Space: O(n²)
  • •Alternative approach: Use suffix automaton or suffix array for O(n) solution

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
countSubstrings('abc');
Expected:
4
Test Case 2
Not run
Input:
countSubstrings('aaa');
Expected:
4
Test Case 3
Not run
Input:
countSubstrings('ababa');
Expected:
16

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit