Open In App

Check if words are sorted according to new order of alphabets

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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




// C++ program to check if words are sorted according to new
// order of alphabets
#include <bits/stdc++.h>
    using namespace std;
 
bool isOrderSorted(string order, vector<string>& words)
{
    // Initialize a hashmap to record the relations between
    // each letter and its ranking in order.
    unordered_map<int, int> mp;
    for (int i = 0; i < order.length(); i++) {
        mp[order[i] - 'a'] = i;
    }
 
    // Iterate over words and compare each pair of adjacent
    // words
    for (int i = 0; i < words.size() - 1; i++) {
 
        // Iterate over each letter to find the first
        // different letter between words[i] and words[i +
        // 1].
        for (int j = 0; j < words[i].length(); j++) {
            // If we do not find a mismatch letter between
            // words[i] and words[i + 1], we need to examine
            // the case when words are like ("addition",
            // "add").
            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 we find the first different letter and
                // the two words are in the wrong order,
                // then we can safely return false.
                if (mp[curr] > mp[next])
                    return false;
                // If we find the first different letter and
                // the two words are in the correct order,
                // then we can exit from the current
                // iteration and proceed to the next pair of
                // words.
                else
                    break;
            }
        }
    }
    // If we reach this point, it means that we have
    // examined all pairs of adjacent words and that they
    // are all sorted. Therefore we can return true.
    return true;
}
 
int main()
{
    // Words in array
    vector<string> words = { "hello", "leetcode" };
 
    // new alphabetical order
    string order = "habcldefgijkmnopqrstuvwxyz";
 
    if (isOrderSorted(order, words))
        cout << "True\n";
    else
        cout << "False\n";
}
 
// // This code is contributed by Rudreshwar Baranwal


Java




import java.io.*;
import java.util.*;
 
class GFG {
    public static boolean isOrderSorted(String order,
                                        List<String> words)
    {
        // Initialize a hashmap to record the relations
        // between each letter and its ranking in order.
        Map<Character, Integer> mp = new HashMap<>();
        for (int i = 0; i < order.length(); i++) {
            mp.put(order.charAt(i), i);
        }
 
        // Iterate over words and compare each pair of
        // adjacent words
        for (int i = 0; i < words.size() - 1; i++) {
            // Iterate over each letter to find the first
            // different letter between words[i] and words[i
            // + 1].
            for (int j = 0; j < words.get(i).length();
                 j++) {
                // If we do not find a mismatch letter
                // between words[i] and words[i + 1], we
                // need to examine the case when words are
                // like ("addition", "add").
                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 we find the first different letter
                    // and the two words are in the wrong
                    // order, then we can safely return
                    // false.
                    if (mp.get(curr) > mp.get(next)) {
                        return false;
                    }
                    // If we find the first different letter
                    // and the two words are in the correct
                    // order, then we can exit from the
                    // current iteration and proceed to the
                    // next pair of words.
                    else {
                        break;
                    }
                }
            }
        }
        // If we reach this point, it means that we have
        // examined all pairs of adjacent words and that
        // they are all sorted. Therefore we can return
        // true.
        return true;
    }
 
    public static void main(String[] args)
    {
        // Words in list
        List<String> words = new ArrayList<>();
        words.add("hello");
        words.add("leetcode");
 
        // new alphabetical order
        String order = "habcldefgijkmnopqrstuvwxyz";
 
        if (isOrderSorted(order, words)) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }
}


Python3




# Function to check whether Words are sorted in given Order
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]
 
        # Find the first difference word1[k] != word2[k].
        for k in range(min(len(word1), len(word2))):
 
            # If they compare false then it's not sorted.
            if word1[k] != word2[k]:
                if Order_index[word1[k]] > Order_index[word2[k]]:
                    return False
                break
        else:
 
            # If we didn't find a first difference, the
            # Words are like ("add", "addition").
            if len(word1) > len(word2):
                return False
 
    return True
 
 
# Program Code
Words = ["hello", "leetcode"]
Order = "habcldefgijkmnopqrstuvwxyz"
 
# Function call to print required answer
print(isAlienSorted(Words, Order))


C#




// C# equivalent
using System;
using System.Collections.Generic;
 
public class GFG {
  public static bool isOrderSorted(string order, List<string> words)
  {
     
    // Initialize a dictionary to record the relations
    // between each letter and its ranking in order.
    Dictionary<char, int> mp = new Dictionary<char, int>();
    for (int i = 0; i < order.Length; i++)
    {
      mp.Add(order[i], i);
    }
 
    // Iterate over words and compare each pair of
    // adjacent words
    for (int i = 0; i < words.Count - 1; i++)
    {
      // Iterate over each letter to find the first
      // different letter between words[i] and words[i
      // + 1].
      for (int j = 0; j < words[i].Length; j++)
      {
        // If we do not find a mismatch letter
        // between words[i] and words[i + 1], we
        // need to examine the case when words are
        // like ("addition", "add").
        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 we find the first different letter
          // and the two words are in the wrong
          // order, then we can safely return
          // false.
          if (mp[curr] > mp[next])
          {
            return false;
          }
          // If we find the first different letter
          // and the two words are in the correct
          // order, then we can exit from the
          // current iteration and proceed to the
          // next pair of words.
          else
          {
            break;
          }
        }
      }
    }
    // If we reach this point, it means that we have
    // examined all pairs of adjacent words and that
    // they are all sorted. Therefore we can return
    // true.
    return true;
  }
 
  public static void Main(string[] args)
  {
     
    // Words in list
    List<string> words = new List<string>();
    words.Add("hello");
    words.Add("leetcode");
 
    // new alphabetical order
    string order = "habcldefgijkmnopqrstuvwxyz";
 
    if (isOrderSorted(order, words))
    {
      Console.WriteLine("True");
    }
    else
    {
      Console.WriteLine("False");
    }
  }
}


Javascript




function isOrderSorted(order, words) {
  // Initialize a hashmap to record the relations between
  // each letter and its ranking in order.
  const mp = {};
  for (let i = 0; i < order.length; i++) {
    mp[order.charCodeAt(i) - 'a'.charCodeAt(0)] = i;
  }
 
  // Iterate over words and compare each pair of adjacent words
  for (let i = 0; i < words.length - 1; i++) {
    // Iterate over each letter to find the first different letter
    // between words[i] and words[i + 1].
    for (let j = 0; j < words[i].length; j++) {
      // If we do not find a mismatch letter between words[i] and words[i + 1],
      // we need to examine the case when words are like ("addition", "add").
      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 we find the first different letter and
        // the two words are in the wrong order,
        // then we can safely return false.
        if (mp[curr] > mp[next])
          return false;
        // If we find the first different letter and
        // the two words are in the correct order,
        // then we can exit from the current iteration
        // and proceed to the next pair of words.
        else
          break;
      }
    }
  }
 
  // If we reach this point, it means that
  // we have examined all pairs of adjacent words
  // and that they are all sorted. Therefore we can return true.
  return true;
}
 
// Words in array
const words = ['hello', 'leetcode'];
 
// new alphabetical order
const order = 'habcldefgijkmnopqrstuvwxyz';
 
if (isOrderSorted(order, words))
  console.log('True');
else
  console.log('False');


Output

True

Time Complexity: O(N), where N is the total number of characters in all words.
Auxiliary Space: O(1)



Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads