Sort Topic Names by Prefix and Number
Updated
Problem statement
You are given an array topics of topic names. Each name has a prefix, one underscore, and a suffix. The prefix is one or more lowercase English letters. The suffix is a nonnegative integer.
Sort the names by prefix first, in alphabetical (dictionary) order. Names with the same prefix are sorted by the value of their suffix as a number, not by its digits as text.
Return all the names in this order. If a name appears more than once, keep every copy. If the input is empty, return an empty array. You can assume no suffix has leading zeros, except the suffix 0 itself.
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"]Prefix aaa comes before prefix bbb, so the three aaa names go first. Sorted as numbers, their suffixes are 2, 5 and 10. The bbb name comes last.
Example 2
topics = ["ab_0","a_100","a_2","a_2"]return = ["a_2","a_2","a_100","ab_0"]Prefix a comes before prefix ab, so all the a names come first. Suffixes only decide the order between names with the same prefix. The repeated name stays in the answer twice.
Example 3
topics = []return = []There are no names, so the answer is an empty array.
Constraints
0 <= topics.length <= 2000.- Every prefix has
1to20lowercase English letters. - Every suffix is an integer from
0to10^9, written with no leading zeros. - Each name contains exactly one underscore.
More Perplexity AI interview questions
- Feature Flags with Rules, Dependencies and ExposureONSITE INTERVIEW · Seen Nov 2026
- In-Memory Filesystem CommandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Out-of-Order Bank Ledger BalancesOA · Seen Nov 2026
- Resource Reconciler: Plan and Apply CreatesPHONE SCREEN · Seen Nov 2026
- Agent Task Dependency TrackerPHONE SCREEN · Seen May 2026
- LLM Provider Pool FailoverPHONE SCREEN · Seen Aug 2025
Similar questions at other companies
- Count Adjacent Symbol Pairs for BPEAmazon · ONSITE INTERVIEW
- Map and Accumulate Learning QueriesPalantir · ONSITE INTERVIEWPalantir interview questions
- Sort Words by LengthMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Compress Consecutive Integer RangesDocuSign · ONSITE INTERVIEWDocuSign interview questions
- Sort Sentence WordsInfosys · ONSITE INTERVIEWInfosys interview questions
- Deduplicate Logs: Keep FirstGoogle · ONSITE INTERVIEWGoogle interview questions
- Check AnagramsDeloitte · ONSITE INTERVIEWDeloitte interview questions
- Check AnagramsBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Check Anagram Pairs Index by IndexExpedia · ONSITE INTERVIEWExpedia interview questions
- Type-Ahead Prefix MatchesNavan · ONSITE INTERVIEWNavan interview questions