Check if there exists any sub-sequence in a string which is not palindrome

Given a string of lowercase English alphabets. The task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 subsequence that is not a palindrome then print YES, otherwise print NO.
Examples:Â
Input : str = "abaab"
Output: YES
Subsequences "ab" or "abaa" or "aab", are not a palindrome.
Input : str = "zzzz"
Output: NO
All possible subsequences are palindrome.
The main observation is that if the string contains at least two distinct characters, then there will always be a subsequence of length at least two which is not a palindrome. Only if all the characters of the string are the same then there will not be any subsequence that is not a palindrome. Because in an optimal way we can choose any two distinct characters from a string and place them in same order one after each to form a non-palindromic string.
Below is the implementation of above approach:Â
C++
// C++ program to check if there exists// at least 1 sub-sequence in a string// which is not palindromeÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromebool isAnyNotPalindrome(string s){    // use set to count number of    // distinct characters    set<char> unique;Â
    // insert each character in set    for (int i = 0; i < s.length(); i++)        unique.insert(s[i]);Â
    // If there is more than 1 unique    // characters, return true    if (unique.size() > 1)        return true;    // Else, return false    else        return false;}Â
// Driver codeint main(){Â Â Â Â string s = "aaaaab";Â
    if (isAnyNotPalindrome(s))        cout << "YES";    else        cout << "NO";Â
    return 0;} |
Java
// Java program to check if there exists// at least 1 sub-sequence in a string// which is not palindromeÂ
import java.util.*;class GFG{         // Function to check if there exists    // at least 1 sub-sequence in a string    // which is not palindrome    static boolean isAnyNotPalindrome(String s)    {        // use set to count number of        // distinct characters        Set<Character> unique=new HashSet<Character>();             // insert each character in set        for (int i = 0; i < s.length(); i++)            unique.add(s.charAt(i));             // If there is more than 1 unique        // characters, return true        if (unique.size() > 1)            return true;        // Else, return false        else            return false;    }         // Driver code    public static void main(String []args)    {        String s = "aaaaab";             if (isAnyNotPalindrome(s))            System.out.println("YES");        else            System.out.println("NO");         }} |
Python3
# Python3 program to check if there exists# at least 1 sub-sequence in a string# which is not palindromeÂ
Â
# Function to check if there exists# at least 1 sub-sequence in a string# which is not palindromedef isAnyNotPalindrome(s):Â
    # use set to count number of    # distinct characters    unique=set() Â
    # insert each character in set    for i in range(0,len(s)):        unique.add(s[i]) Â
    # If there is more than 1 unique    # characters, return true    if (len(unique) > 1):        return True             # Else, return false    else:        return FalseÂ
Â
# Driver codeif __name__=='__main__':Â Â Â Â s = "aaaaab"Â
    if (isAnyNotPalindrome(s)):        print("YES")     else:        print("NO") Â
# This code is contributed by# ihritik |
C#
// C# program to check if there exists // at least 1 sub-sequence in a string // which is not palindrome using System;using System.Collections.Generic; Â
class GFG {          // Function to check if there exists     // at least 1 sub-sequence in a string     // which is not palindrome     static bool isAnyNotPalindrome(String s)     {         // use set to count number of         // distinct characters         HashSet<char> unique=new HashSet<char>();              // insert each character in set         for (int i = 0; i < s.Length; i++)             unique.Add(s[i]);              // If there is more than 1 unique         // characters, return true         if (unique.Count > 1)             return true;         // Else, return false         else            return false;     }          // Driver code     public static void Main(String []args)     {         String s = "aaaaab";              if (isAnyNotPalindrome(s))             Console.WriteLine("YES");         else            Console.WriteLine("NO");     } } Â
// This code contributed by Rajput-Ji |
Javascript
<script>Â
// JavaScript program to check if there exists// at least 1 sub-sequence in a string// which is not palindromeÂ
// Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromefunction isAnyNotPalindrome(s){    // use set to count number of    // distinct characters    var unique = new Set();Â
    // insert each character in set    for (var i = 0; i < s.length; i++)        unique.add(s[i]);Â
    // If there is more than 1 unique    // characters, return true    if (unique.size > 1)        return true;    // Else, return false    else        return false;}Â
// Driver codevar s = "aaaaab";if (isAnyNotPalindrome(s))    document.write( "YES");else    document.write( "NO");Â
Â
</script> |
YES
Complexity Analysis:
- Time Complexity: O(N * logN), where N is the length of the string.
- Auxiliary Space: O(N)
Another approach: Two pointer
Another approach to check if there exists any sub-sequence in a string that is not palindrome is to use the two-pointer technique. We can use two pointers, one pointing to the beginning of the string and the other pointing to the end of the string. We can then move the pointers towards each other until they meet, and check if any non-palindromic sub-sequence exists in the string.
Steps that were to follow the above approach:
- Initialize two pointers, left and right, to the start and end of the string, respectively.
- While left < right, do the following:
- If the character at index left is not equal to the character at index right, then we have found a sub-sequence that is not a palindrome, so return true.
- Otherwise, increment left and decrement right.
- If we have not found any sub-sequence that is not a palindrome, return false.
Below is the code to implement the above steps:
C++
// C++ code to implement the above approach#include <iostream>#include <string>using namespace std;Â
bool hasNonPalindromeSubsequence(string str){Â Â Â Â int i = 0, j = str.length() - 1;Â
    // move the pointers towards each other until they meet    while (i < j) {        // if a non-palindromic sub-sequence is found,        // return true        if (str[i] != str[j])            return true;        i++;        j--;    }Â
    // if no non-palindromic sub-sequence is found, return    // false    return false;}Â
// Driver's codeint main(){Â Â Â Â string str = "aaaaab";Â
    if (hasNonPalindromeSubsequence(str))        cout << "Yes";    else        cout << "No";Â
    return 0;} |
Java
import java.util.*;Â
public class Main {Â Â Â Â public static boolean hasNonPalindromeSubsequence(String str) {Â Â Â Â Â Â Â Â int i = 0, j = str.length() - 1;Â
        // move the pointers towards each other until they meet        while (i < j) {            // if a non-palindromic sub-sequence is found,            // return true            if (str.charAt(i) != str.charAt(j))                return true;            i++;            j--;        }Â
        // if no non-palindromic sub-sequence is found, return false        return false;    }Â
    public static void main(String[] args) {        String str = "aaaaab";Â
        if (hasNonPalindromeSubsequence(str))            System.out.println("Yes");        else            System.out.println("No");    }} |
Python3
# Python code for the above approachdef hasNonPalindromeSubsequence(string):Â Â Â Â i = 0Â Â Â Â j = len(string) - 1Â
    # Move the pointers towards each other until they meet    while i < j:        # If a non-palindromic subsequence is found, return True        if string[i] != string[j]:            return True        i += 1        j -= 1Â
    # If no non-palindromic subsequence is found, return False    return FalseÂ
# Driver codestr = "aaaaab"Â
if hasNonPalindromeSubsequence(str):Â Â Â Â print("Yes")else:Â Â Â Â print("No")Â
# THIS CODE IS CONTRIBUTED KIRTI AGARWAL |
C#
// C# code to implement the above approachusing System;Â
class GFG{    static bool HasNonPalindromeSubsequence(string str)    {        int i = 0, j = str.Length - 1;                 // move the pointers towards each other until they meet        while (i < j)        {            // if a non-palindromic sub-sequence is found,            // return true            if (str[i] != str[j])                return true;            i++;            j--;        }        // if no non-palindromic sub-sequence is found, return        // false        return false;    }Â
    // Driver's code    public static void Main()    {        string str = "aaaaab";        if (HasNonPalindromeSubsequence(str))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }} |
Javascript
function hasNonPalindromeSubsequence(str) {Â Â Â Â let i = 0;Â Â Â Â let j = str.length - 1;Â
    // Move the pointers towards each other until they meet    while (i < j) {        // If a non-palindromic subsequence is found, return true        if (str[i] !== str[j]) {            return true;        }        i++;        j--;    }Â
    // If no non-palindromic subsequence is found, return false    return false;}Â
// Driver codeconst str = 'aaaaab';Â
if (hasNonPalindromeSubsequence(str)) {Â Â Â Â console.log('Yes');} else {Â Â Â Â console.log('No');} |
Yes
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



