Given a list of full names (each name contains one or more words), sort the list in lexicographic order by the last name (the last token in each string). If two last names are equal, preserve the original relative order (stable sort) or use the full name as a tiebreaker.
Input:
names = ["Asha Sharma", "Ravi Kumar", "Priya Singh", "Arun Mehta"]
Output:
["Arun Mehta", "Asha Sharma", "Priya Singh", "Ravi Kumar"]
Explanation:
Last names are ["Sharma","Kumar","Singh","Mehta"]; sorted order by last name yields the output above.
Input:
names = ["Anjali Rao", "Anjali Rao Kumar", "Bhavana Rao", "Karan Patel"]
Output:
["Anjali Rao", "Bhavana Rao", "Anjali Rao Kumar", "Karan Patel"]
Explanation:
The last token for the first three names is ["Rao","Rao","Kumar","Patel"]; ties among "Rao" are resolved by full-name comparison or stable order.
Sorting by last name reduces to sorting by a key extracted from each string: the final whitespace-separated token. Using a stable sort preserves original order for equal keys.
from typing import List
classSolution:
defsortNamesByLast(self, names: List[str]) -> List[str]:
deflast(name: str) -> str:
parts = name.split()
return parts[-1] if parts else name
return sorted(names, key=lambda x: (last(x), x))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pubstructSolution;
impl Solution {
pubfnsort_names_by_last(mut names: Vec<String>) -> Vec<String> {
names.sort_by(|a, b| {
let la = a.split_whitespace().last().unwrap_or("");
let lb = b.split_whitespace().last().unwrap_or("");
match la.cmp(lb) {
std::cmp::Ordering::Equal => a.cmp(b),
ord => ord,
}
});
names
}
}
1
2
3
4
5
6
7
8
9
10
exportclassSolution {
sortNamesByLast(names: string[]):string[] {
returnnames.sort((a, b) => {
constla=a.trim().split(/\s+/).slice(-1)[0];
constlb=b.trim().split(/\s+/).slice(-1)[0];
if (la===lb) returna.localeCompare(b);
returnla.localeCompare(lb);
});
}
}