LeetCode 3083: Existence of a Substring in a String and Its Reverse Solution
Master LeetCode problem 3083 (Existence of a Substring in a String and Its Reverse), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3083. Existence of a Substring in a String and Its Reverse
Problem Explanation
Explanation:
To solve this problem, we can iterate through each possible substring of length 2 in the given string. For each substring, we check if its reverse is also present in the original string. If we find such a substring, we return true. If we exhaust all possibilities and do not find any such substring, we return false.
- Initialize a set to store all unique substrings of length 2 from the original string.
- Iterate over the original string, considering each pair of adjacent characters as a substring of length 2.
- Check if the reverse of the current substring is present in the original string.
- If found, return true.
- If no such substring is found after iterating through all possibilities, return false.
Time Complexity:
The time complexity of this approach is O(n^2), where n is the length of the input string.
Space Complexity:
The space complexity is O(n) to store the unique substrings of length 2.
:
Solution Code
class Solution {
public boolean isSubstringReverse(String s) {
Set<String> substrings = new HashSet<>();
for (int i = 0; i < s.length() - 1; i++) {
String substring = s.substring(i, i + 2);
if (substrings.contains(new StringBuilder(substring).reverse().toString())) {
return true;
}
substrings.add(substring);
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3083 (Existence of a Substring in a String and Its Reverse)?
This page provides optimized solutions for LeetCode problem 3083 (Existence of a Substring in a String and Its Reverse) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3083 (Existence of a Substring in a String and Its Reverse)?
The time complexity for LeetCode 3083 (Existence of a Substring in a String and Its Reverse) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3083 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3083 in Java, C++, or Python.