FastPrepDecode Words with Anagram Keys

Decode Words with Anagram Keys

Cresta logoCresta● MediumFULLTIMEOA
Learn

Problem statement

You are given a list of lowercase knownWords and an encodedMessage. For this exercise, assume each encoded token is a rearrangement of a known word’s letters that preserves that word’s first letter.

Decode each token independently. A word is a candidate exactly when it has the same first letter and the same number of every letter as the token. If several known words are candidates, choose the lexicographically smallest one. Duplicate dictionary entries have no additional effect.

Every nonempty message token is guaranteed to have at least one candidate. The message is empty or contains nonempty tokens separated by single spaces, with no leading or trailing space. Return the decoded words joined by single spaces, or the empty string for an empty message.

Function

decodeMessage(knownWords: String[], encodedMessage: String) → String

Examples

Example 1

knownWords = ["cat","dog"]encodedMessage = "cta dgo"return = "cat dog"

The tokens preserve c and d and decode to cat dog.

Example 2

knownWords = ["east","eats","tea"]encodedMessage = "etsa tae"return = "east tea"

Both east and eats match the first token; choose east. The second token decodes to tea.

Example 3

knownWords = []encodedMessage = ""return = ""

An empty message has no tokens to decode.

Constraints

  • 0 <= knownWords.length <= 2000.
  • Each known word and encoded token contains1..40 lowercase English letters.
  • The total number of letters in the dictionary is at most 8 × 10^4.
  • The message contains at most2000 tokens and at most 10^5 characters including spaces.

More Cresta problems

See Cresta hiring insights
public String decodeMessage(String[] knownWords, String encodedMessage) {
    // write your code here
}
knownWords["cat","dog"]
encodedMessage"cta dgo"
expected"cat dog"
Checking account…