FastPrepCustom Sort a String

Custom Sort a String

Meta logoMeta● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a string order whose distinct characters define a custom order, rearrange the characters of s to follow that order. Characters listed in order must appear in their custom order, with all copies of one listed character together.

For this exercise, put characters absent from order after all listed characters and keep those remaining characters in their original relative order from s. Return the resulting string.

Function

customSortString(order: String, s: String) → String

Examples

Example 1

order = "egbca"s = "abbceeeg"return = "eeegbbca"

Custom order ranks e, then g, b, c, and a. Grouping the source characters in that order gives eeegbbca.

Example 2

order = "cba"s = "abcd"return = "cbad"

The listed characters become cba. The unlisted d follows them.

Example 3

order = "bca"s = "xxacbxy"return = "bcaxxxy"

Listed characters become bca. The unlisted characters retain their original sequence xxxy.

Constraints

  • 1 <= order.length <= 26.
  • 1 <= s.length <= 200.
  • Both strings contain lowercase English letters.
  • Every character in order is distinct.

More Meta problems

See Meta hiring insights
public String customSortString(String order, String s) {
    // Write your code here
}
order"egbca"
s"abbceeeg"
expected"eeegbbca"
Checking account…