Existence of a Substring in a String and Its Reverse Problem
#3083
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3083.
Given a string s, find any substring of length 2 which is also present in the reverse of s.
Return true if such a substring exists, and false otherwise.
Example 1:
Input: s = "leetcode"
Output: true
Explanation: Substring "ee" is of length 2 which is also present in reverse(s) == "edocteel".
Example 2:
Input: s = "abcba"
Output: true
Explanation: All of the substrings of length 2 "ab", "bc", "cb", "ba" are also present in reverse(s) == "abcba".
Example 3:
Input: s = "abcd"
Output: false
Explanation: There is no substring of length 2 in s, which is also present in the reverse of s.
Constraints:
1 <= s.length <= 100sconsists only of lowercase English letters.
Solution
Approach: Hash Table
Store every length-2 substring of the reversed string in a set. Because the reverse of s[i] s[i+1] is s[i+1] s[i], it is enough to insert the pair (s[i+1], s[i]) for each i. Then scan the length-2 substrings of s and return true as soon as one is in the set.
Complexity: O(n) time, O(26^2) space.
class Solution:
def isSubstringPresent(self, s: str) -> bool:
st = {(s[i + 1], s[i]) for i in range(len(s) - 1)}
return any((s[i], s[i + 1]) in st for i in range(len(s) - 1))