FastPrepGet Min Cost Data 🍊

Get Min Cost Data 🍊

Amazon logoAmazon● MediumINTERNOA
Learn

Problem statement

You are given a string data containing lowercase English letters and question marks. Replace every ? with a lowercase English letter.

The cost of a position is the number of earlier positions containing the same letter. Equivalently, if a letter appears f times in the completed string, it contributes f * (f - 1) / 2 to the total cost.

Return a completed string with the minimum possible total cost. If several completed strings have that minimum cost, return the lexicographically smallest one.

Function

getMinCostData(data: String) β†’ String

Examples

Example 1

data = "aaaa?aaaa"return = "aaaabaaaa"

Replacing ? with b creates no additional equal-letter pair and is the lexicographically smallest minimum-cost choice.

Example 2

data = "??????"return = "abcdef"

Using six distinct letters gives total cost 0. Sorting the chosen letters produces the smallest such string, abcdef.

Example 3

data = "abcd?"return = "abcde"

Choosing a through d would repeat an existing letter and add cost. The smallest unused letter is e, so abcde has minimum cost 0.

Constraints

  • 1 <= data.length <= 10^5
  • data contains lowercase English letters and ? only.
  • data contains at least one ?.

More Amazon problems

See Amazon hiring insights
public String getMinCostData(String data) {
  // write your code here
}
data"aaaa?aaaa"
expected"aaaabaaaa"
Checking account…