Start learning free

LESSON 623 OF 673 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in Python: Numeric Sort with key=int

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

def sortLines(self, lines: List[str]) -> str:

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Pass a key function to sorted that converts each line to int. The output keeps the original string form, only the comparison happens on the integer value.

The full solution:
class Solution:
    def sortLines(self, lines):
        sortedLines = sorted(lines, key=int)
        return "\n".join(sortedLines)

STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Python, explained

    Problem overview

    This version adds the effect of sort -n. Every input line is the text form of an integer that fits in 32 bits: an optional leading -, no +, and leading zeros such as "007" are allowed. The method sortLines sorts the lines by numeric value, ascending, and returns the original strings joined by "\n".

    For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". Lines with the same numeric value keep their original relative order, and an empty list gives the empty string.

    Approach: compare numbers, keep the text

    Sorting the strings directly compares them character by character, so "100" comes before "20" because "1" is smaller than "2". The same input sorted as plain text gives "10\n100\n20\n3". That is the trap in this lesson.

    The cure is not to convert the list into integers: the answer must contain the original text, so "007" has to come out as "007", not "7". Instead, sorted accepts a key function. It calls the function once for each element and compares the results, but it returns the original elements. Passing int as the key makes the comparison numeric while the output stays text.

    Step by step

    1. Create sortedLines from sorted(lines, key=int). Each line is turned into a number only for the comparison, so 20 lands before 100.
    2. Return the sorted lines joined with a newline between each two.

    The solution in Python

    class Solution:
        def sortLines(self, lines):
            sortedLines = sorted(lines, key=int)
            return "\n".join(sortedLines)
    

    Some details of this short solution matter:

    • int is a class, but any callable that takes one element and returns something comparable works as a key. Writing key=int passes the function itself; key=int() would be an error, because it calls int immediately with no argument.
    • int("007") is 7 and int("-5") is -5, so leading zeros and the minus sign are handled without any parsing code.
    • sorted is stable: elements whose keys are equal stay in the order they had in the input. The lesson requires exactly this, and it needs no extra code.
    • Python integers have no fixed size, so 32-bit values never overflow.

    Complexity

    The time is O(n log n) comparisons for n lines, plus one int conversion per line. Python computes each key once, not once per comparison. The extra space is O(n) for the new list and the stored keys.

    Edge cases and common mistakes

    linesnumeric sort (this lesson)plain text sort
    ["100", "20", "3", "10"]"3\n10\n20\n100""10\n100\n20\n3"
    ["10", "9", "1"]"1\n9\n10""1\n10\n9"
    ["007", "7", "-5", "10", "-12"]"-12\n-5\n007\n7\n10""-12\n-5\n007\n10\n7"
    • In the third row, "007" and "7" have the same value, so they stay in input order, with "007" first. Had the input been ["7", "007"], the output would keep "7" first.
    • Negative numbers work naturally: -12 is smaller than -5. As text, "-12" would also come first, but only by accident of the characters, not because of the values.
    • Don't convert the lines to integers and join them: "\n".join needs strings, and the output would lose the leading zeros.
    • An empty string is not an integer: int("") raises ValueError. The statement guarantees that every line is a valid number, so the solution does not guard against it.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free