#3083
Existence of a Substring in a String and Its Reverse
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking each substring against the reversed string, we can use a set to store all substrings of length 2 from the original string and check for matches in the reversed string.
⚙️
Algorithm
3 steps- 1Step 1: Create a set to store all substrings of length 2 from the original string s.
- 2Step 2: Loop through the reversed string and check if any substring of length 2 exists in the set.
- 3Step 3: If a match is found, return true. If no matches are found after checking all, return false.
solution.py10 lines
1# Full working Python code
2s = 'leetcode'
3substrings = {s[i:i+2] for i in range(len(s) - 1)}
4reverse_s = s[::-1]
5for i in range(len(reverse_s) - 1):
6 if reverse_s[i:i+2] in substrings:
7 print(True)
8 break
9else:
10 print(False)ℹ
Complexity note: The time complexity is O(n) because we traverse the string a couple of times (once for creating the set and once for checking the reversed string). The space complexity is O(n) due to the storage of substrings in the set.
- 1Using a set allows for O(1) average time complexity for lookups, making the optimal solution much faster than the brute force approach.
- 2Understanding how to manipulate strings and utilize data structures like sets can greatly improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.