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 <= 100s consists only of lowercase English letters.This approach involves sorting the array first, then using a two-pointer technique to solve the problem. By sorting, we can utilize the sorted order to efficiently find pairs or triplets that meet our requirements.
This C code uses the qsort function to sort the array. A pointer approach is then used to find a pair that sums to the target. It iterates from both ends towards the center.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as we're sorting in place.
In this approach, a hash map (or dictionary) is used to keep track of the elements we have seen so far and their respective indices. This allows for efficient look-up to find pairs that sum to the target value without needing to sort the array.
This C code creates a basic hash table using an array of pointers to store key-value pairs. The target complement is computed for each element, and we check if it has been previously added, ensuring a quick lookup.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) on average due to hash map operations.
Space Complexity: O(n) as we need to store entries in the hash table.
| Approach | Complexity |
|---|---|
| Approach 1: Using Sorting | Time Complexity: O(n log n) due to sorting. |
| Approach 2: Using Hashing | Time Complexity: O(n) on average due to hash map operations. |
Permutation in String | Leetcode #567 | Anagram of string s1 in string s2 • Techdose • 68,348 views views
Watch 9 more video solutions →Practice Existence of a Substring in a String and Its Reverse with our built-in code editor and test cases.
Practice on FleetCode