← Questions
Sort strings by length, then merge two sorted lists
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Sep 2025. It tests sorting, merge and strings.
You get two unsorted lists of strings. Return one list with all the strings sorted by length, shortest first. Strings of equal length keep their original relative order, where the original order is the first list followed by the second. Follow-up: if each list already arrives sorted that way, merge them in linear time.
Interface
Unless you agree on a different interface with the interviewer, assume:
sort_by_length(list1: list[str], list2: list[str]) -> list[str]-
merge_by_length(list1: list[str], list2: list[str]) -> list[str]: both inputs already sorted by length with the same tie rule.
Example
sort_by_length(["kiwi", "fig", "banana"], ["date", "apple", "ab"])
-> ["ab", "fig", "kiwi", "date", "apple", "banana"] # "kiwi" before "date": list1 first
merge_by_length(["ox", "cat", "lion"], ["a", "dog", "bear", "zebra"])
-> ["a", "ox", "cat", "dog", "lion", "bear", "zebra"] # on equal length, take from list1
Constraints
- Up to
10^5strings in total. - Strings may repeat and may be empty.
Clarifying questions
- How are equal-length strings ordered?
- Can I use the language's sort, or should I write one?
- Is extra memory allowed in the merge?
What a strong answer covers
- A stable sort keyed on length over the concatenation, O(n log n); why stability gives the tie rule for free.
- If lengths are small, a counting sort by length, O(n + max length).
- The merge: two pointers, taking from
list1when lengths are equal so the result stays stable, O(n + m). - In-place merging versus a new list, and the cost of each.
- Tests: empty lists, all the same length, empty strings.
Follow-ups
- Merge
ksorted lists (a heap). - Break ties alphabetically instead.
- The lists are too large for memory.
Where it's asked
- Apple · Technical phone screen · Last asked Sep 2025
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
