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
š§ Prerequisites
š ļø 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
š¤ Output