FastPrepOne-Mismatch Consensus String

One-Mismatch Consensus String

IMC Trading logoIMC Trading● MediumFULLTIMEOA
Learn

Problem statement

You are given N words in words. Every word contains exactly K lowercase English letters.

Return a string of length K that differs from every input word at no more than one position. Characters are compared at matching positions; rearranging letters is not allowed.

For this exercise, assume the lexicographically smallest valid string is returned when several exist. For this exercise, assume the answer is an empty string when no valid length-K string exists.

Function

consensusString(words: String[]) → String

Examples

Example 1

words = ["ab","ba"]return = "aa"

Both mixed strings aa and bb work; aa is smaller.

Example 2

words = ["abc","axc","aby"]return = "abc"

Differences occur at two distinct positions, forcing abc.

Example 3

words = ["abc","xyz"]return = ""

The words differ at three positions, so no answer can be within one of both.

Example 4

words = ["zzz","zzz"]return = "azz"

Changing the first character to a produces the smallest valid word.

Constraints

  • 2 <= N <= 10^5
  • 1 <= K <= 10^5
  • 2 <= N * K <= 10^6
  • Every word has length K and contains only lowercase English letters.

More IMC Trading problems

See IMC Trading hiring insights
public String consensusString(String[] words) {
    // Write your solution here.
}
words["ab","ba"]
expected"aa"
Checking account…