Given a sentence as a string sentence, return its words sorted in alphabetical order, joined into a single string with single spaces.
The comparison is case-insensitive, but each word keeps its original casing in the output.
Function Signature
def alphabetical_sentence(sentence: str) -> str:
Rules
-
Two words are compared by their lowercase forms, character by character. A word that is a prefix of another comes first (
"app"
before
"apple"
).
-
Words whose lowercase forms are equal (for example
"Apple"
and
"apple"
, or two copies of
"the"
) keep the order they had in the input.
-
The output separates words with single spaces and has no leading or trailing spaces.
Constraints
-
1 <= len(sentence) <= 10^4
-
sentence
contains only English letters and spaces.
-
Words are separated by single spaces.
-
There are no leading or trailing spaces.
Examples
Input: sentence = "the quick brown fox jumps over the lazy dog"
Output: "brown dog fox jumps lazy over quick the the"
All nine words are already lowercase, so this is a plain alphabetical sort. The two copies of "the" end up next to each other at the end.
Input: sentence = "Banana apple Cherry"
Output: "apple Banana Cherry"
Compared in lowercase, "apple" < "banana" < "cherry". Each word keeps its own casing, so "Banana" and "Cherry" stay capitalized.
Input: sentence = "b A a B"
Output: "A a b B"
"A" and "a" tie on the key "a" and keep their input order, so "A" comes first. "b" and "B" tie on "b", and "b" appeared first in the input, so it stays ahead of "B".