Check if words are sorted according to new order of alphabets
Last Updated :
14 Mar, 2023
Given a sequence of Words and the Order of the alphabet. The order of the alphabet is some permutation of lowercase letters. The task is to check whether the given words are sorted lexicographically according to order of alphabet. Return “True” if it is, otherwise “False”.
Examples:
Input : Words = [“hello”, “leetcode”], Order = “habcldefgijkmnopqrstuvwxyz”
Output : true
Input : Words = [“word”, “world”, “row”], Order = “abcworldefghijkmnpqstuvxyz”
Output : false
Explanation : As ‘d’ comes after ‘l’ in Order, thus words[0] > words[1], hence the sequence is unsorted.
Approach: The words are sorted lexicographically if and only if adjacent words are sorted. This is because order is transitive i:e if a <= b and b <= c, implies a <= c. So our goal it to check whether all adjacent words a and b have a <= b. To check whether for two adjacent words a and b, a <= b holds we can find their first difference. For example, “seen” and “scene” have a first difference of e and c. After this, we compare these characters to the index in order. We have to deal with the blank character effectively. If for example, we are comparing “add” to “addition”, this is a first difference of (NULL) vs “i”.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
bool isOrderSorted(string order, vector<string>& words)
{
unordered_map< int , int > mp;
for ( int i = 0; i < order.length(); i++) {
mp[order[i] - 'a' ] = i;
}
for ( int i = 0; i < words.size() - 1; i++) {
for ( int j = 0; j < words[i].length(); j++) {
if (j >= words[i + 1].length())
return false ;
if (words[i][j] != words[i + 1][j]) {
int curr = words[i][j] - 'a' ;
int next = words[i + 1][j] - 'a' ;
if (mp[curr] > mp[next])
return false ;
else
break ;
}
}
}
return true ;
}
int main()
{
vector<string> words = { "hello" , "leetcode" };
string order = "habcldefgijkmnopqrstuvwxyz" ;
if (isOrderSorted(order, words))
cout << "True\n" ;
else
cout << "False\n" ;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static boolean isOrderSorted(String order,
List<String> words)
{
Map<Character, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < order.length(); i++) {
mp.put(order.charAt(i), i);
}
for ( int i = 0 ; i < words.size() - 1 ; i++) {
for ( int j = 0 ; j < words.get(i).length();
j++) {
if (j >= words.get(i + 1 ).length()) {
return false ;
}
if (words.get(i).charAt(j)
!= words.get(i + 1 ).charAt(j)) {
char curr = words.get(i).charAt(j);
char next = words.get(i + 1 ).charAt(j);
if (mp.get(curr) > mp.get(next)) {
return false ;
}
else {
break ;
}
}
}
}
return true ;
}
public static void main(String[] args)
{
List<String> words = new ArrayList<>();
words.add( "hello" );
words.add( "leetcode" );
String order = "habcldefgijkmnopqrstuvwxyz" ;
if (isOrderSorted(order, words)) {
System.out.println( "True" );
}
else {
System.out.println( "False" );
}
}
}
|
Python3
def isAlienSorted(Words, Order):
Order_index = {c: i for i, c in enumerate (Order)}
for i in range ( len (Words) - 1 ):
word1 = Words[i]
word2 = Words[i + 1 ]
for k in range ( min ( len (word1), len (word2))):
if word1[k] ! = word2[k]:
if Order_index[word1[k]] > Order_index[word2[k]]:
return False
break
else :
if len (word1) > len (word2):
return False
return True
Words = [ "hello" , "leetcode" ]
Order = "habcldefgijkmnopqrstuvwxyz"
print (isAlienSorted(Words, Order))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static bool isOrderSorted( string order, List< string > words)
{
Dictionary< char , int > mp = new Dictionary< char , int >();
for ( int i = 0; i < order.Length; i++)
{
mp.Add(order[i], i);
}
for ( int i = 0; i < words.Count - 1; i++)
{
for ( int j = 0; j < words[i].Length; j++)
{
if (j >= words[i + 1].Length)
{
return false ;
}
if (words[i][j] != words[i + 1][j])
{
char curr = words[i][j];
char next = words[i + 1][j];
if (mp[curr] > mp[next])
{
return false ;
}
else
{
break ;
}
}
}
}
return true ;
}
public static void Main( string [] args)
{
List< string > words = new List< string >();
words.Add( "hello" );
words.Add( "leetcode" );
string order = "habcldefgijkmnopqrstuvwxyz" ;
if (isOrderSorted(order, words))
{
Console.WriteLine( "True" );
}
else
{
Console.WriteLine( "False" );
}
}
}
|
Javascript
function isOrderSorted(order, words) {
const mp = {};
for (let i = 0; i < order.length; i++) {
mp[order.charCodeAt(i) - 'a' .charCodeAt(0)] = i;
}
for (let i = 0; i < words.length - 1; i++) {
for (let j = 0; j < words[i].length; j++) {
if (j >= words[i + 1].length)
return false ;
if (words[i][j] !== words[i + 1][j]) {
const curr = words[i].charCodeAt(j) - 'a' .charCodeAt(0);
const next = words[i + 1].charCodeAt(j) - 'a' .charCodeAt(0);
if (mp[curr] > mp[next])
return false ;
else
break ;
}
}
}
return true ;
}
const words = [ 'hello' , 'leetcode' ];
const order = 'habcldefgijkmnopqrstuvwxyz' ;
if (isOrderSorted(order, words))
console.log( 'True' );
else
console.log( 'False' );
|
Time Complexity: O(N), where N is the total number of characters in all words.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...