Check if a string is made up of K alternating characters

Given a string str and an integer K, the task is to check if it is made up of K alternating characters.

Examples:

Input: str = “acdeac”, K = 4
Output: Yes

Input: str = “abcdcab”, K = 2
Output: No

Approach: In order for the string to be made up of K alternating characters, it must satisfy the following conditions:



  1. All the characters at (i + mK) indices must be same, where i is the current index and mK represents the mth multiple of K. It means that after every K indices, the character must get repeated.
  2. The adjacent characters must not be the same. This is because if the string is of type “AAAAA”, where a single character is repeated any number of time, the above condition will get matched, but the answer must be ‘No’ in this case.

    Below code is the implementation of the above approach:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ implementation of the approach
      
    #include <bits/stdc++.h>
    using namespace std;
      
    // Function to check if a string
    // is made up of k alternating characters
    bool isKAlternating(string s, int k)
    {
        if (s.length() < k)
            return false;
      
        int checker = 0;
      
        // Check if all the characters at
        // indices 0 to K-1 are different
        for (int i = 0; i < k; i++) {
      
            int bitAtIndex = s[i] - 'a';
      
            // If that bit is already set in
            // checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
      
            // Otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
      
        for (int i = k; i < s.length(); i++)
            if (s[i - k] != s[i])
                return false;
      
        return true;
    }
      
    // Driver code
    int main()
    {
        string str = "acdeac";
        int K = 4;
      
        if (isKAlternating(str, K))
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
      
        return 0;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java implementation of the approach
    class GFG{
       
    // Function to check if a String
    // is made up of k alternating characters
    static boolean isKAlternating(String s, int k)
    {
        if (s.length() < k)
            return false;
       
        int checker = 0;
       
        // Check if all the characters at
        // indices 0 to K-1 are different
        for (int i = 0; i < k; i++) {
       
            int bitAtIndex = s.charAt(i) - 'a';
       
            // If that bit is already set in
            // checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
       
            // Otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
       
        for (int i = k; i < s.length(); i++)
            if (s.charAt(i - k) != s.charAt(i) )
                return false;
       
        return true;
    }
       
    // Driver code
    public static void main(String[] args)
    {
        String str = "acdeac";
        int K = 4;
       
        if (isKAlternating(str, K))
            System.out.print("Yes" +"\n");
        else
            System.out.print("No" +"\n"); 
    }
    }
      
    // This code is contributed by sapnasingh4991

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python 3 implementation of the approach
       
    # Function to check if a string
    # is made up of k alternating characters
    def isKAlternating( s, k):
        if (len(s) < k):
            return False
       
        checker = 0
       
        # Check if all the characters at
        # indices 0 to K-1 are different
        for i in range( k):
       
            bitAtIndex = ord(s[i]) - ord('a')
       
            # If that bit is already set in
            # checker, return false
            if ((checker & (1 << bitAtIndex)) > 0):
                return False
       
            # Otherwise update and continue by
            # setting that bit in the checker
            checker = checker | (1 << bitAtIndex)
       
        for i in range(k,len(s)):
            if (s[i - k] != s[i]):
                return False
       
        return True
       
    # Driver code
    if __name__ =="__main__":
      
        st = "acdeac"
        K = 4
       
        if (isKAlternating(st, K)):
            print ("Yes")
        else:
            print ("No")
       
    # This code is contributed by chitranayal   

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# implementation of the approach
    using System;
      
    class GFG{
      
    // Function to check if a String
    // is made up of k alternating characters
    static bool isKAlternating(String s, int k)
    {
        if (s.Length < k)
            return false;
      
        int checker = 0;
      
        // Check if all the characters at
        // indices 0 to K-1 are different
        for (int i = 0; i < k; i++) {
      
            int bitAtIndex = s[i] - 'a';
      
            // If that bit is already set in
            // checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
      
            // Otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
      
        for (int i = k; i < s.Length; i++)
            if (s[i - k] != s[i] )
                return false;
      
        return true;
    }
      
    // Driver code
    public static void Main() 
    {
        String str = "acdeac";
        int K = 4;
      
        if (isKAlternating(str, K))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
    }
      
    // This article contributed by AbhiThakur

    chevron_right

    
    

    Output:

    Yes
    

    Time Complexity: 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.




    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.