212. Python Program to Merge Two Sorted Lists Without sort()
MediumPhase 2 · Practice
This one takes a few steps. You know every tool in it: a while loop, list positions and slices.
Overview
Merging two sorted lists is a classic interview question. It is also the main step of merge sort, a fast way to sort big lists.
Problem Statement
Marta has two piles of test papers. Each pile is already in order by mark, from small to big. Marta wants one pile in order, without sorting everything again.
- Each line of the input is already sorted from small to big.
- Build one list with all the numbers of both lines, sorted from small to big.
- Do not use
sort()orsorted(). Compare the numbers yourself, one step at a time. - Print
Merged: <numbers>, with one space between the numbers.
Examples
Example 1. Input:
1 4 9
2 3 10
gives:
Merged: 1 2 3 4 9 10
Why: at each step, the smaller of the two front numbers goes next: 1, 2, 3, 4 and then 9. After that, only 10 is left.
Example 2. Input:
5
1 2 3
gives:
Merged: 1 2 3 5
Why: 1, 2 and 3 are all smaller than 5. When the second line runs out, the 5 that is left goes at the end.
Input
Two lines. Each line holds whole numbers sorted from small to big, with one space between them (1 number or more on each line). The numbers can be negative, and they can repeat. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Merged:, a space, and all the numbers from small to big, with one space between them. The tests try 7 different inputs, also negative numbers and numbers that repeat.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.