3083. Existence of a Substring in a String and Its Reverse LeetCode Solution

In this guide, you will get 3083. Existence of a Substring in a String and Its Reverse LeetCode Solution with the best time and space complexity. The solution to Existence of a Substring in a String and Its Reverse problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Existence of a Substring in a String and Its Reverse solution in C++
  4. Existence of a Substring in a String and Its Reverse solution in Java
  5. Existence of a Substring in a String and Its Reverse solution in Python
  6. Additional Resources
3083. Existence of a Substring in a String and Its Reverse LeetCode Solution image

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

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 <= 100
s consists only of lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n^2)
  • Space Complexity: O(n)

3083. Existence of a Substring in a String and Its Reverse LeetCode Solution in C++

class Solution {
 public:
  bool isSubstringPresent(string s) {
    const string reversed = {s.rbegin(), s.rend()};
    for (int i = 0; i + 2 <= s.length(); ++i)
      if (reversed.find(s.substr(i, 2)) != string::npos)
        return true;
    return false;
  }
};
/* code provided by PROGIEZ */

3083. Existence of a Substring in a String and Its Reverse LeetCode Solution in Java

class Solution {
  public boolean isSubstringPresent(String s) {
    String reversed = new StringBuilder(s).reverse().toString();
    for (int i = 0; i + 2 <= s.length(); ++i)
      if (reversed.contains(s.substring(i, i + 2)))
        return true;
    return false;
  }
}
// code provided by PROGIEZ

3083. Existence of a Substring in a String and Its Reverse LeetCode Solution in Python

class Solution:
  def isSubstringPresent(self, s: str) -> bool:
    return any(s[i:i + 2] in s[::-1] for i in range(len(s) - 1))
# code by PROGIEZ

Additional Resources

See also  664. Strange Printer LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.