Sort by Length and Lexicographically
EasyPractice library · +10 XPsortingstrings
Given a list of strings, sort them based on two criteria: first, by their length in ascending order. If two strings have the same length, sort them lexicographically (alphabetically) in ascending order. Print the sorted list of strings, each on a new line.
Input
The first line contains an integer N, the number of strings. The next N lines each contain one string.
Output
Print the N strings, one per line, in the specified sorted order.
Constraints
1 <= N <= 50 Each string consists of lowercase English letters ('a'-'z'). The length of each string is between 1 and 50, inclusive.
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 c a b apple banana
Output
a b c apple banana
Sorts by length (1, 1, 1, 5, 6) then alphabetically for same lengths (a, b, c).
Example 2
Input
4 cat dog apple banana
Output
cat dog apple banana
Sorts by length (3, 3, 5, 6) then alphabetically for length 3 (cat, dog).
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 c a b apple banana
Example 2 input
4 cat dog apple banana