Existence of a Substring in a String and Its Reverse - Problem

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.

Note: A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcba"
Output: true
💡 Note: The 2-character substring "ab" appears at the beginning of the original string and also appears at the beginning of the reversed string "abcba"
Example 2 — No Match
$ Input: s = "abcd"
Output: false
💡 Note: Original string has substrings "ab", "bc", "cd". Reversed string "dcba" has substrings "dc", "cb", "ba". No common 2-character substring exists.
Example 3 — Single Match
$ Input: s = "leetcode"
Output: true
💡 Note: The substring "ee" appears in the original string. The reversed string "edocteel" also contains "ee", so return true.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters only

Visualization

Tap to expand
Substring in String and Its Reverse INPUT Original String s: a b c b a 0 1 2 3 4 Reversed String: a b c b a Length-2 Substrings: "ab" "bc" "cb" "ba" s = "abcba" ALGORITHM STEPS 1 Create Hash Set Store all length-2 substrings HashSet: {"ab","bc","cb","ba"} O(n) time to build set 2 Reverse Each Pair For each substr, reverse it "ab" reversed --> "ba" "bc" reversed --> "cb" 3 Check in Set Is reversed in original set? "ba" in Set? --> YES! Found match at first check 4 Return Result Match found: return true FINAL RESULT Match Found: "ab" in s "ba" in reverse In original "abcba": a b c b a In reversed "abcba": a b c b a Output: true Key Insight: A substring appears in both s and reverse(s) if and only if the reversed substring exists in s. Using a HashSet allows O(1) lookup, making the overall time complexity O(n) where n is string length. Space Complexity: O(n) for storing substrings in the hash set. TutorialsPoint - Existence of a Substring in a String and Its Reverse | Hash Set Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen