Custom Sort String
Learn this problemProblem statement
AWS provides several utilities for language processing. Develop a helper service to sort a list of strings based on a custom order of characters.
More formally, you are given a custom alphabet system that consists of exactly k characters. Their sorted alphabetical order is given by a string of distinct characters, order. An array arr contains n strings to sort according to the special ordering. Each string in arr contains only characters in order.
Note: A string x = x1x2 ... xn is lexicographically smaller than string y = y1y2 ... ym if either n < m and x1 = y1, x2 = y2, ... xn = ym, or exists some number r (1 β€ r < n, r < m), such that x1 = y1, x2 = y2, ... xr-1 = yr-1, xr < yr.
Function
customSortString(order: String, arr: String[]) β String[]
Complete the function customSortString in the editor below.
customSortString has the following parameters:
string order: the custom order alphabet ofkcharactersstring arr[n]: the strings to sort
Returns
string(s): the sorted strings
π§‘ Endless gratitude to the best π·spikeπ·! π§‘
Examples
Example 1
order = "9AacB"arr = ["BBBBa", "BBBB9", "B9ca", "Aa999", "B9A", "B", "B9A"]return = ["Aa999", "B", "B9A", "B9A", "B9ca", "BBB89", "BBBBa"]
order = "9AacB" so 'A' comes before 'B', '9' comes before 'B', 'A' comes before 'c', 'c' comes before 'B', '9' comes before 'a'.
The sorted order of strings is ["Aa999", "B", "B9A", "B9A", "B9ca", "BBB89", "BBBBa"].
Example 2
order = "yYaAbBl"arr = ["Yay", "yaY", "lyab", "lyab", "b", "bay"]return = ["yaY", "Yay", "b", "bay", "lyab", "lyaB"]
order = "yYaAbB1" so 'y' comes before 'Y', 'Y' is before 'b', 'b' is before '1', 'y' is before 'a' and 'b' is before 'B'.
The sorted order of strings is ["yaY", "Yay", "b", "bay", "lyab", "lyaB"].
Example 3
order = "7BbAz"arr = ["Abb", "A7z", "z7AAAA", "BbbABB"]return = ["BbbABB", "A7z", "Abb", "z7AAAA"]
Constraints
- 1 β€ k β€ 62
- 1 β€ n β€ 10^5
- The sum of lengths of all strings in arr does not exceed 10^6.
- All characters of arr[] are present in order.
- All characters of order are distinct and consist of [a-zA-Z0-9] only.
More Amazon problems
- Resolve Task DependenciesONSITE INTERVIEW Β· Seen Jul 2026
- Shortest Distance on a Circular Bus RouteOA Β· Seen Jul 2026
- Longest Increasing Subsequence With Bounded Adjacent DifferenceONSITE INTERVIEW Β· Seen Jul 2026
- Search in a Rotated Sorted ArrayONSITE INTERVIEW Β· Seen Jul 2026
- Sliding Window MaximumONSITE INTERVIEW Β· Seen Jul 2026
- Merge IntervalsOA Β· Seen Jul 2026
- Sort Bug Report FrequenciesOA Β· Seen Jul 2026
- Drone Delivery RouteOA Β· Seen Jul 2026