Prepin
Log in

Assess whether two words are arranged in lexicographic order.

Approach / Explanation

This question requires you to assess whether two given words are arranged in lexicographic order. To clarify, lexicographic, or dictionary order, refers to the sequence in which words are organized based on their individual letters, sorted according to their position in the alphabet. For instance, "apple" precedes "banana" in lexicographic order. It is important to note that uppercase and lowercase letters may be sorted differently because of their varying ASCII values. Your objective is to create an algorithm that accepts two words and evaluates whether they are sorted in lexicographic order. Key aspects to keep in mind while addressing this task: Grasping the concept of lexicographic order. Addressing case sensitivity in the algorithm. Strategies for comparing the order of two words.

Suggested Answer

This can be accomplished easily by utilizing Python's built-in comparison function. Below is an example of the code: def areWordsSorted ( word1 , word2 ) : if word1 . lower ( ) < word2 . lower ( ) : return True else : return False In this example, the function areWordsSorted(word1, word2) accepts two words. The .lower() method is utilized to convert the strings to lowercase, preventing inaccuracies in comparisons due to case variations. The < operator is employed to check if word1 precedes word2 in lexicographical order.

Alternative Answer

A more thorough method involves comparing the words character by character. Below is an example code snippet demonstrating this approach: def areWordsSorted ( word1 , word2 ) : word1 = word1 . lower ( ) word2 = word2 . lower ( ) # compare the words character by character for a , b in zip ( word1 , word2 ) : if a < b : return True elif a > b : return False # If we've reached this point, it means word1 is either equal to word2 or is a prefix of word2 if len ( word1 ) <= len ( word2 ) : return True else : return False This function operates similarly to the previous one. It first converts both words to lowercase, then compares each character of the words sequentially. If it encounters a character in word1 that is lexicographically greater than the corresponding character in word2 , it returns False . If it completes the comparison without finding such a pair, it returns True if word1 is shorter than or equal in length to word2 ; otherwise, it returns False . This handles scenarios where one word is a prefix of the other, such as 'apple' and 'apples'.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.