FastPrepSort Words by a Custom Alphabet

Sort Words by a Custom Alphabet

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given a custom alphabet order and an array of lowercase words. Sort the words lexicographically under that custom order.

Compare the first position where two words differ using the characters' ranks in alphabet. If one word is a prefix of the other, the shorter word comes first. Return the sorted words.

Function

sortWordsByAlphabet(alphabet: String, words: String[]) → String[]

Examples

Example 1

alphabet = "zyxwvutsrqponmlkjihgfedcba"words = ["apple","app","banana"]return = ["banana","app","apple"]

Under the reversed alphabet, b precedes a. Among the two a-words, app is a prefix of apple.

Example 2

alphabet = "bacdefghijklmnopqrstuvwxyz"words = ["ab","aa","ba","b"]return = ["b","ba","ab","aa"]

b-words come before a-words; prefixes come first; and within the a-words, the second character b ranks before a.

Example 3

alphabet = "abcdefghijklmnopqrstuvwxyz"words = []return = []

An empty word array remains empty.

Constraints

  • alphabet is a permutation of the 26 lowercase English letters.
  • 0 <= words.length <= 100000.
  • Every word is nonempty and contains only lowercase English letters.
  • The total number of characters across words is at most 200000.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String[] sortWordsByAlphabet(String alphabet, String[] words) {
    // Write your code here.
}
alphabet"zyxwvutsrqponmlkjihgfedcba"
words["apple","app","banana"]
expected["banana", "app", "apple"]
Checking account…