Check if the string contains consecutive letters and each letter occurs exactly once
Last Updated :
15 Sep, 2023
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++
#include <bits/stdc++.h>
using namespace std;
bool check(string s)
{
int l = s.length();
sort(s.begin(), s.end());
for ( int i = 1; i < l; i++) {
if (s[i] - s[i - 1] != 1)
return false ;
}
return true ;
}
int main()
{
string str = "dcef" ;
if (check(str))
cout << "Yes\n" ;
else
cout << "No\n" ;
str = "xyza" ;
if (check(str))
cout << "Yes\n" ;
else
cout << "No\n" ;
return 0;
}
|
Java
import java.util.*;
class GfG {
static boolean check( char s[])
{
int l = s.length;
Arrays.sort(s);
for ( int i = 1 ; i < l; i++) {
if (s[i] - s[i - 1 ] != 1 )
return false ;
}
return true ;
}
public static void main(String[] args)
{
String str = "dcef" ;
if (check(str.toCharArray()) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
String str1 = "xyza" ;
if (check(str1.toCharArray()) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def check(s):
l = len (s)
s = ''.join( sorted (s))
for i in range ( 1 , l):
if ord (s[i]) - ord (s[i - 1 ]) ! = 1 :
return False
return True
if __name__ = = "__main__" :
string = "dcef"
if check(string):
print ( "Yes" )
else :
print ( "No" )
string = "xyza"
if check(string):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections;
class GfG {
static bool check( char [] s)
{
int l = s.Length;
Array.Sort(s);
for ( int i = 1; i < l; i++) {
if (s[i] - s[i - 1] != 1)
return false ;
}
return true ;
}
public static void Main()
{
string str = "dcef" ;
if (check(str.ToCharArray()) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
String str1 = "xyza" ;
if (check(str1.ToCharArray()) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function check(s)
{
let l = s.length;
s.sort();
for (let i = 1; i < l; i++) {
if ((s[i].charCodeAt() - s[i - 1].charCodeAt()) != 1)
return false ;
}
return true ;
}
let str = "dcef" ;
if (check(str.split( '' )) == true )
document.write( "Yes" + "</br>" );
else
document.write( "No" + "</br>" );
let str1 = "xyza" ;
if (check(str1.split( '' )) == true )
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(N logN)
Auxiliary Space: O(1)
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 Equation:
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:
C++
#include<bits/stdc++.h>
using namespace std;
bool check(string str)
{
int min = INT_MAX;
int max = -INT_MAX;
int sum = 0;
for ( int i = 0; i < str.size(); i++)
{
int ascii = str[i];
if (ascii < 96 || ascii > 122)
return false ;
sum += ascii;
if (min > ascii)
min = ascii;
if (max < ascii)
max = ascii;
}
min -= 1;
int eSum = ((max * (max + 1)) / 2) -
((min * (min + 1)) / 2);
return sum == eSum;
}
int main()
{
string str = "dcef" ;
if (check(str))
cout << ( "Yes" );
else
cout << ( "No" );
string str1 = "xyza" ;
if (check(str1))
cout << ( "\nYes" );
else
cout << ( "\nNo" );
}
|
Java
public class GFG {
public static boolean check(String str)
{
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int sum = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
int ascii = ( int )str.charAt(i);
if (ascii < 96 || ascii > 122 )
return false ;
sum += ascii;
if (min > ascii)
min = ascii;
if (max < ascii)
max = ascii;
}
min -= 1 ;
int eSum
= ((max * (max + 1 )) / 2 )
- ((min * (min + 1 )) / 2 );
return sum == eSum;
}
public static void main(String[] args)
{
String str = "dcef" ;
if (check(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
String str1 = "xyza" ;
if (check(str1))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
import sys
def check( str ):
min = sys.maxsize
max = - sys.maxsize - 1
sum = 0
for i in range ( len ( str )):
ascii = str [i]
if ( ord (ascii) < 96 or ord (ascii) > 122 ):
return False
sum + = ord (ascii)
if ( min > ord (ascii)):
min = ord (ascii)
if ( max < ord (ascii)):
max = ord (ascii)
min - = 1
eSum = ((( max * ( max + 1 )) / / 2 ) -
(( min * ( min + 1 )) / / 2 ))
return sum = = eSum
if __name__ = = '__main__' :
str = "dcef"
if (check( str )):
print ( "Yes" )
else :
print ( "No" )
str1 = "xyza"
if (check(str1)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool check( string str)
{
int min = Int32.MaxValue;
int max = Int32.MinValue;
int sum = 0;
for ( int i = 0; i < str.Length; i++)
{
int ascii = ( int )str[i];
if (ascii < 96 || ascii > 122)
return false ;
sum += ascii;
if (min > ascii)
min = ascii;
if (max < ascii)
max = ascii;
}
min -= 1;
int eSum
= ((max * (max + 1)) / 2)
- ((min * (min + 1)) / 2);
return sum == eSum;
}
static void Main()
{
string str = "dcef" ;
if (check(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
string str1 = "xyza" ;
if (check(str1))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function check( str) {
var min = Number.MAX_VALUE;
var max = Number.MIN_VALUE;
var sum = 0;
for (i = 0; i < str.length; i++) {
var ascii = parseInt( str.charCodeAt(i));
if (ascii < 96 || ascii > 122)
return false ;
sum += ascii;
if (min > ascii)
min = ascii;
if (max < ascii)
max = ascii;
}
min -= 1;
var eSum = parseInt((max * (max + 1)) / 2) - ((min * (min + 1)) / 2);
return sum == eSum;
}
var str = "dcef" ;
if (check(str))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
var str1 = "xyza" ;
if (check(str1))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
bool check(string s)
{
unordered_set< char > seen;
for ( char c : s) {
if (seen.count(c)) {
return false ;
}
seen.insert(c);
}
char min_char = *min_element(s.begin(), s.end());
char max_char = *max_element(s.begin(), s.end());
return (max_char - min_char + 1 == s.length());
}
int main()
{
string str = "dcef" ;
if (check(str))
cout << "Yes\n" ;
else
cout << "No\n" ;
str = "xyza" ;
if (check(str))
cout << "Yes\n" ;
else
cout << "No\n" ;
return 0;
}
|
Java
import java.util.HashSet;
public class Main {
static boolean check(String s) {
HashSet<Character> seen = new HashSet<>();
for ( char c : s.toCharArray()) {
if (seen.contains(c)) {
return false ;
}
seen.add(c);
}
char minChar = s.charAt( 0 );
for ( char c : s.toCharArray()) {
minChar = ( char ) Math.min(minChar, c);
}
char maxChar = s.charAt( 0 );
for ( char c : s.toCharArray()) {
maxChar = ( char ) Math.max(maxChar, c);
}
return (maxChar - minChar + 1 == s.length());
}
public static void main(String[] args) {
String str = "dcef" ;
if (check(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
str = "xyza" ;
if (check(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def check(s):
seen = set ()
for c in s:
if c in seen:
return False
seen.add(c)
min_char = min (s)
max_char = max (s)
return ( ord (max_char) - ord (min_char) + 1 = = len (s))
if __name__ = = '__main__' :
str = "dcef"
if (check( str )):
print ( "Yes" )
else :
print ( "No" )
str = "xyza"
if (check( str )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
public static bool Check( string s)
{
HashSet< char > seen = new HashSet< char >();
foreach ( char c in s)
{
if (seen.Contains(c))
{
return false ;
}
seen.Add(c);
}
char min_char = s.Min();
char max_char = s.Max();
return (max_char - min_char + 1 == s.Length);
}
public static void Main()
{
string str = "dcef" ;
if (Check(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
str = "xyza" ;
if (Check(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
function check(s) {
let seen = new Set();
for (let c of s) {
if (seen.has(c)) {
return false ;
}
seen.add(c);
}
let minChar = s.charAt(0);
for (let c of s) {
minChar = Math.min(minChar, c);
}
let maxChar = s.charAt(0);
for (let c of s) {
maxChar = Math.max(maxChar, c);
}
return (maxChar.charCodeAt(0) - minChar.charCodeAt(0) + 1 === s.length);
}
let str = "dcef" ;
if (check(str))
console.log( "Yes" );
else
console.log( "No" );
str = "xyza" ;
if (check(str))
console.log( "Yes" );
else
console.log( "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.
Share your thoughts in the comments
Please Login to comment...