Open In App

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:  

Below is the implementation of the above approach:  




// 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;
}




// 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");
    }
}




# 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




// 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




<script>
    // Javascript program to implement
    // the above approach
     
    // Function to check if
    // the condition holds
    function check(s)
    {
  
        // Get the length of the string
        let l = s.length;
  
        // sort the given string
        s.sort();
  
        // Iterate for every index and
        // check for the condition
        for (let i = 1; i < l; i++) {
  
            // If are not consecutive
            if ((s[i].charCodeAt() - s[i - 1].charCodeAt()) != 1)
                return false;
        }
  
        return true;
    }
     
    // 1st example
    let str = "dcef";
    if (check(str.split('')) == true)
      document.write("Yes" + "</br>");
    else
      document.write("No" + "</br>");
 
    // 2nd example
    let str1 = "xyza";
 
    if (check(str1.split('')) == true)
      document.write("Yes");
    else
      document.write("No");
       
      // This code is contributed by mukesh07.
</script>

Output
Yes
No








Time complexity: O(N logN)

Auxiliary Space: O(1)

Efficient approach: 

 MAX_VALUE*(MAX_VALUE+1)/2 - (MIN_VALUE-1)*((MIN_VALUE-1)+1)/2

Below is the implementation of the above approach: 




// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
bool check(string str)
{
    int min = INT_MAX;
    int max = -INT_MAX;
    int sum = 0;
     
    // For all the characters of the string
    for(int i = 0; i < str.size(); i++)
    {
         
        // Find the ascii value of the character
        int ascii = str[i];
         
        // Check 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
int main()
{
     
    // 1st example
    string str = "dcef";
    if (check(str))
        cout << ("Yes");
    else
        cout << ("No");
 
    // 2nd example
    string str1 = "xyza";
    if (check(str1))
        cout << ("\nYes");
    else
        cout << ("\nNo");
}
 
// This code is contributed by amreshkumar3




// 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 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)




# Python3 program to implement
# the above approach
import sys
 
def check(str):
     
    min = sys.maxsize
    max = -sys.maxsize - 1
    sum = 0
 
    # For all the characters of the string
    for i in range(len(str)):
         
        # Find the ascii value of the character
        ascii = str[i]
 
        # Check if its a valid character,
        # if not then return false
        if (ord(ascii) < 96 or ord(ascii) > 122):
            return False
 
        # Calculate sum of all the
        # characters ascii values
        sum += ord(ascii)
 
        # Find minimum ascii value
        # from the string
        if (min > ord(ascii)):
            min = ord(ascii)
 
        # Find maximum ascii value
        # from the string
        if (max < ord(ascii)):
            max = ord(ascii)
 
    # To get the previous element
    # of the minimum ASCII value
    min -= 1
 
    # Take the expected sum
    # from the above equation
    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
if __name__ == '__main__':
     
    # 1st example
    str = "dcef"
     
    if (check(str)):
        print("Yes")
    else:
        print("No")
 
    # 2nd example
    str1 = "xyza"
     
    if (check(str1)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by mohit kumar 29




// C# program to implement
// the above approach
using System;
class GFG
{
     
    static bool check(string str)
    {
        int min = Int32.MaxValue;
        int max = Int32.MinValue;
        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[i];
  
            // check 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
  static void Main()
  {
     
    // 1st example
    string str = "dcef";
    if (check(str))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
 
    // 2nd example
    string str1 = "xyza";
 
    if (check(str1))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
  }
}
 
// This code is contributed by divyesh072019.




<script>
// javascript program to implement
// the above approach
  
 
    function check( str) {
        var min = Number.MAX_VALUE;
        var max = Number.MIN_VALUE;
        var sum = 0;
 
        // for all the characters of the string
        for (i = 0; i < str.length; i++) {
 
            // find the ascii value of the character
            var ascii = parseInt( str.charCodeAt(i));
 
            // check 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
        var eSum = parseInt((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
     
 
        // 1st example
        var str = "dcef";
        if (check(str))
            document.write("Yes<br/>");
        else
            document.write("No<br/>");
 
        // 2nd example
        var str1 = "xyza";
 
        if (check(str1))
            document.write("Yes");
        else
            document.write("No");
 
// This code contributed by Rajput-Ji
</script>

Output
Yes
No








Time Complexity: O(N) 
 Auxiliary Space: O(1)

Approach (Using set):

In this approach, we use an unordered set to keep track of the letters we’ve seen so far. We iterate through the string s, and for each character c in the string, we check if it has already been seen in the set. If it has, this means that the string does not contain each letter exactly once, so we return false. If it has not been seen, we insert the letter into the set.

After we’ve finished iterating through the string and checking for duplicate letters, we use the min_element and max_element functions from the algorithm library to get the minimum and maximum characters in the string, respectively. We then check if the difference between the maximum and minimum characters plus one is equal to the length of the string. If it is, this means that the string contains consecutive letters, so we return true. Otherwise, we return false.

Below is the implementation of the above approach:




// 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)
{
    // use unordered set to keep track of seen letters
    unordered_set<char> seen;
 
    for (char c : s) {
        // check if letter has already been seen
        if (seen.count(c)) {
            return false;
        }
        seen.insert(c); // insert letter into set
    }
 
    // get minimum character in string
    char min_char = *min_element(s.begin(), s.end());
    // get maximum character in string
    char max_char = *max_element(s.begin(), s.end());
 
    // check if consecutive letters
    return (max_char - min_char + 1 == s.length());
}
 
// 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;
}




import java.util.HashSet;
 
public class Main {
    // Function to check if the condition holds
    static boolean check(String s) {
        // Use HashSet to keep track of seen letters
        HashSet<Character> seen = new HashSet<>();
 
        for (char c : s.toCharArray()) {
            // Check if letter has already been seen
            if (seen.contains(c)) {
                return false;
            }
            seen.add(c); // Insert letter into set
        }
 
        // Get minimum character in string
        char minChar = s.charAt(0);
        for (char c : s.toCharArray()) {
            minChar = (char) Math.min(minChar, c);
        }
 
        // Get maximum character in string
        char maxChar = s.charAt(0);
        for (char c : s.toCharArray()) {
            maxChar = (char) Math.max(maxChar, c);
        }
 
        // Check if consecutive letters
        return (maxChar - minChar + 1 == s.length());
    }
 
    // 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
        str = "xyza";
 
        if (check(str))
            System.out.println("Yes");
        else
            System.out.println("No");
 
        // This code is contributed by Shivam Tiwari
    }
}




# Function to check if
# the condition holds
 
 
def check(s):
    # use set to keep track of seen letters
    seen = set()
 
    for c in s:
        # check if letter has already been seen
        if c in seen:
            return False
        seen.add(c)  # insert letter into set
 
    # get minimum character in string
    min_char = min(s)
    # get maximum character in string
    max_char = max(s)
 
    # check if consecutive letters
    return (ord(max_char) - ord(min_char) + 1 == len(s))
 
 
# Driver code
if __name__ == '__main__':
    # 1st example
    str = "dcef"
    if (check(str)):
        print("Yes")
    else:
        print("No")
 
    # 2nd example
    str = "xyza"
    if (check(str)):
        print("Yes")
    else:
        print("No")




using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG
{
    // Function to check if the condition holds
    public static bool Check(string s)
    {
        // Use HashSet<char> to keep track of seen letters
        HashSet<char> seen = new HashSet<char>();
 
        foreach (char c in s)
        {
            // Check if letter has already been seen
            if (seen.Contains(c))
            {
                return false;
            }
            seen.Add(c); // Insert letter into set
        }
 
        // Get minimum character in string
        char min_char = s.Min();
        // Get maximum character in string
        char max_char = s.Max();
 
        // Check if consecutive letters
        return (max_char - min_char + 1 == s.Length);
    }
 
    // Driver code
    public static void Main()
    {
        // 1st example
        string str = "dcef";
        if (Check(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
 
        // 2nd example
        str = "xyza";
 
        if (Check(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
 
        // This code is contributed by Shivam Tiwari
    }
}




// Function to check if the condition holds
function check(s) {
    // Use Set to keep track of seen letters
    let seen = new Set();
 
    for (let c of s) {
        // Check if letter has already been seen
        if (seen.has(c)) {
            return false;
        }
        seen.add(c); // Insert letter into set
    }
 
    // Get minimum character in string
    let minChar = s.charAt(0);
    for (let c of s) {
        minChar = Math.min(minChar, c);
    }
 
    // Get maximum character in string
    let maxChar = s.charAt(0);
    for (let c of s) {
        maxChar = Math.max(maxChar, c);
    }
 
    // Check if consecutive letters
    return (maxChar.charCodeAt(0) - minChar.charCodeAt(0) + 1 === s.length);
}
 
// Driver code
// 1st example
let str = "dcef";
if (check(str))
    console.log("Yes");
else
    console.log("No");
 
// 2nd example
str = "xyza";
 
if (check(str))
    console.log("Yes");
else
    console.log("No");
 
// This code is contributed by Shivam Tiwari

Output
Yes
No

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(k), where k is the number of distinct characters in the string.


Article Tags :