FastPrepSort Topic Names by Prefix and Number

Sort Topic Names by Prefix and Number

Perplexity AI logoPerplexity AI● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Each topic name consists of a nonempty lowercase English-letter prefix, one underscore, and a nonnegative integer suffix. Sort the names by prefix in ascending lexicographic order. Within the same prefix, sort by the numeric value of the suffix, rather than its string representation.

Return all names in that order, preserving duplicate names. Return an empty array for empty input. For this exercise, assume suffixes have no leading zeros except the single digit 0.

Function

sortTopics(topics: String[]) → String[]

Examples

Example 1

topics = ["aaa_10","bbb_1","aaa_5","aaa_2"]return = ["aaa_2","aaa_5","aaa_10","bbb_1"]

The aaa prefix comes before bbb; its numeric suffixes are 2, 5 and 10.

Example 2

topics = ["ab_0","a_100","a_2","a_2"]return = ["a_2","a_2","a_100","ab_0"]

A complete prefix is compared before numeric suffixes. Duplicate names are retained.

Example 3

topics = []return = []

An empty input has no names to order.

Constraints

  • For this exercise, assume 0 <= topics.length <= 2000.
  • Every prefix contains 1 to 20 lowercase English letters.
  • Every suffix is a canonical decimal integer from 0 to 10^9.
  • Each name contains exactly one underscore.

More Perplexity AI problems

See Perplexity AI hiring insights
public String[] sortTopics(String[] topics) {
    // Write your code here.
}
topics["aaa_10","bbb_1","aaa_5","aaa_2"]
expected["aaa_2", "aaa_5", "aaa_10", "bbb_1"]
Checking account…