Check if the string contains consecutive letters and each letter occurs exactly once

Given string str. The task is to check if the string contains consecutive letters and each letter occurs exactly once.

Examples:

Input: str = “fced”
Output: Yes

The string contains ‘c’, ‘d’, ‘e’ and ‘f’ which are consecutive letters.

Input: str = “xyz”
Output: Yes



Input: str = “abd”
Output: No

Approach:

The following steps can be followed to solve the problem:

  • Sort the given string in ascending order.
  • Check if s[i]-s[i-1]==1, for every index i from 1 to n-1.
  • If the condition holds for every index, print “Yes”, else print “No”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if
// the condition holds
bool check(string s)
{
  
    // Get the length of the string
    int l = s.length();
  
    // sort the given string
    sort(s.begin(), s.end());
  
    // Iterate for every index and
    // check for the condition
    for (int i = 1; i < l; i++) {
  
        // If are not consecutive
        if (s[i] - s[i - 1] != 1)
            return false;
    }
  
    return true;
}
  
// Driver code
int main()
{
  
    // 1st example
    string str = "dcef";
    if (check(str))
        cout << "Yes\n";
    else
        cout << "No\n";
  
    // 2nd example
    str = "xyza";
  
    if (check(str))
        cout << "Yes\n";
    else
        cout << "No\n";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GfG {
  
    // Function to check if
    // the condition holds
    static boolean check(char s[])
    {
  
        // Get the length of the string
        int l = s.length;
  
        // sort the given string
        Arrays.sort(s);
  
        // Iterate for every index and
        // check for the condition
        for (int i = 1; i < l; i++) {
  
            // If are not consecutive
            if (s[i] - s[i - 1] != 1)
                return false;
        }
  
        return true;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // 1st example
        String str = "dcef";
        if (check(str.toCharArray()) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
  
        // 2nd example
        String str1 = "xyza";
  
        if (check(str1.toCharArray()) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement 
# the above approach 
  
# Function to check if 
# the condition holds 
def check(s): 
  
    # Get the length of the string 
    l = len(s) 
  
    # sort the given string 
    s = ''.join(sorted(s)) 
  
    # Iterate for every index and 
    # check for the condition 
    for i in range(1, l): 
  
        # If are not consecutive 
        if ord(s[i]) - ord(s[i - 1]) != 1
            return False
  
    return True
  
# Driver code 
if __name__ == "__main__":
  
    # 1st example 
    string = "dcef"
      
    if check(string): 
        print("Yes"
    else:
        print("No"
  
    # 2nd example 
    string = "xyza"
  
    if check(string): 
        print("Yes"
    else:
        print("No"
  
# This code is contributed by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections;
  
class GfG {
  
    // Function to check if
    // the condition holds
    static bool check(char[] s)
    {
  
        // Get the length of the string
        int l = s.Length;
  
        // sort the given string
        Array.Sort(s);
  
        // Iterate for every index and
        // check for the condition
        for (int i = 1; i < l; i++) {
  
            // If are not consecutive
            if (s[i] - s[i - 1] != 1)
                return false;
        }
  
        return true;
    }
  
    // Driver code
    public static void Main()
    {
  
        // 1st example
        string str = "dcef";
        if (check(str.ToCharArray()) == true)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
  
        // 2nd example
        String str1 = "xyza";
  
        if (check(str1.ToCharArray()) == true)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by Ryuga

chevron_right


Output:

Yes
No

Time complexity: O(N logN)

Efficient approach:

  • Find max and min ascii values of the string’s characters
  • find the sum of the ascii values of all the characters from the string
  • so if a sequence of characters are a(ascii = 96) to d(ascii = 99) then, the result expected sum should be (sum from 0 to 99) minus (sum of 0 to 95)
  • Mathematical Equiation:
     MAX_VALUE*(MAX_VALUE+1)/2 - (MIN_VALUE-1)*((MIN_VALUE-1)+1)/2 
  • check whether the calculated sum and the expected sum is equal or not

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
public class GFG {
  
    public static boolean check(String str)
    {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int sum = 0;
  
        // for all the characters of the string
        for (int i = 0; i < str.length(); i++) {
  
            // find the ascii value of the character
            int ascii = (int)str.charAt(i);
  
            // check if if its a valid character,
            // if not then return false
            if (ascii < 96 || ascii > 122)
                return false;
  
            // calculate sum of all the
            // characters ascii values
            sum += ascii;
  
            // find minimum ascii value
            // from the string
            if (min > ascii)
                min = ascii;
  
            // find maximum ascii value
            // from the string
            if (max < ascii)
                max = ascii;
        }
  
        // To get the previous element
        // of the minimum ASCII value
        min -= 1;
  
        // take the expected sum
        // from the above equation
        int eSum
            = ((max * (max + 1)) / 2)
              - ((min * (min + 1)) / 2);
  
        // check if the expected sum is
        // equals to the calculated sum or not
        return sum == eSum;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // 1st example
        String str = "dcef";
        if (check(str))
            System.out.println("Yes");
        else
            System.out.println("No");
  
        // 2nd example
        String str1 = "xyza";
  
        if (check(str1))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Arijit Basu(ArijitXfx)

chevron_right


Output:

Yes
No

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.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.