Given a string S consisting of lowercase English alphabets, the task is to find the longest substring from the given string such that no two adjacent characters are neighbouring English alphabets.
Examples:
Input: S = “aabdml”
Output: “bdm”
Explanation: Substring “bdm” is the longest substring which satisfies the given condition.Input: S = “abc”
Output: “a”
Explanation: Substrings “a”, “b”, “c” satisfies the given condition. Print any one of them.
Approach: Follow the steps below to solve the problem:
- Initialize an empty string, say T, to store all the temporary substrings during iteration.
- Initialize another string, say ans, to store the longest substring as per the given conditions and a variable, say len, to store the length of the longest substring.
- Append the first character of the string to ans.
- Traverse the string in the range of indices [1, S.length()] and perform the following operations:
- If the absolute difference between ASCII values of the adjacent characters is 1, then update ans and the length of the longest string and set T equal to the current character for the next iteration.
- Otherwise, append the current character to string T.
- Check again for the longest substring and update the values accordingly.
- Print the longest substring obtained in variable ans.
Below is the implementation of the above approach:
C++
// C++ program for // the above approach #include <bits/stdc++.h> using namespace std; // Function to find the longest substring // satisfying the given condition void findSubstring(string S) { // Stores all temporary substrings string T = ""; // Stores the longest substring string ans = ""; // Stores the length // of the substring T int l = 0; // Stores the first // character of string S T += S[0]; // Traverse the string for (int i = 1; i < S.length(); i++) { // If the absolute difference is 1 if (abs(S[i] - S[i - 1]) == 1) { // Update the length of // substring T l = T.length(); // Update the longest substring if (l > ans.length()) { ans = T; } T = ""; T += S[i]; } // Otherwise, stores the current // character else { T += S[i]; } } // Again checking for // longest substring // and update accordingly l = (int)T.length(); if (l > (int)ans.length()) { ans = T; } // Print the longest substring cout << ans << endl; } // Driver Code int main() { // Given string string S = "aabdml"; // Function call to find // the longest substring // satisfying given condition findSubstring(S); return 0; } |
bdm
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

