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

Given a string s, you need to determine if there exists any substring of length 2 that appears in both the original string and its reverse.

For example, if s = "abcd", its reverse is "dcba". You need to check if any 2-character substring from the original string also exists in the reversed string.

Goal: Return true if such a common substring exists, false otherwise.

Note: A substring is a contiguous sequence of characters within a string. The same substring can appear multiple times and at different positions.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "leetcode"
โ€บ Output: true
๐Ÿ’ก Note: The substring "ee" appears in both the original string "leetcode" and its reverse "edocteel" (at positions different from each other).
example_2.py โ€” No Match Case
$ Input: s = "abcdef"
โ€บ Output: false
๐Ÿ’ก Note: Original: "abcdef", Reversed: "fedcba". No 2-character substring from original ("ab", "bc", "cd", "de", "ef") appears in reversed ("fe", "ed", "dc", "cb", "ba").
example_3.py โ€” Palindrome Case
$ Input: s = "abcba"
โ€บ Output: true
๐Ÿ’ก Note: The substring "ab" from original appears as "ba" in reverse, and "bc" from original appears as "cb" in reverse. Both are valid matches.

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of lowercase English letters only
  • Note: If string length < 2, return false as no 2-character substring exists

Visualization

Tap to expand
๐Ÿ” The Mirror Detective StorySecret Message"abcba"abbccbba๐Ÿชž Magic MirrorReverses Text"abcba"(same as original)Detective's Notebookโœ“ Step 1: Check "ab" โ†’ reverse "ba" Not seen before, add "ab" to notesโœ“ Step 2: Check "bc" โ†’ reverse "cb" Not seen before, add "bc" to notes๐ŸŽฏ Step 3: Check "cb" โ†’ reverse "bc" FOUND "bc" in notes! MATCH!Case Solved! โœจFound the match!
Understanding the Visualization
1
Read the Secret Message
You have a secret message written on paper
2
Use the Magic Mirror
Hold the message up to a special mirror that shows the reverse
3
Smart Detective Work
Instead of writing down all codes from both sides, you read the original and immediately check if each 2-letter code's reverse was already seen
4
Eureka Moment
The moment you find a match, you've solved the case!
Key Takeaway
๐ŸŽฏ Key Insight: The detective doesn't need to write down all reversed codes separately. Instead, for each original code, they immediately check if they've seen its reverse before. This one-pass approach is both elegant and efficient!
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
42.4K Views
Medium Frequency
~12 min Avg. Time
1.8K 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