Third-Longest Word in Array
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
You receive a list of alphabetic words str_arr containing at least three entries. Order every entry from longest character count down to shortest character count and return the word that lands in third place (0-based index 2 of the ordered sequence).
Apply these ordering rules:
- A word with strictly more characters always precedes a word with fewer characters.
- Whenever two or more words share the exact same character count, preserve the sequence in which they originally appeared from left to right in str_arr (do not sort equal-length words alphabetically, and do not collapse duplicate lengths or identical words).
Examples
Example 1
Input: str_arr = ["maple", "birch", "redwood", "oak"]
Output: "birch"
Explanation: Character counts are 5, 5, 7, 3. "redwood" (7) takes 1st place, "maple" (5) and "birch" (5) retain their initial order to take 2nd and 3rd place, and "oak" (3) lands 4th. The 3rd entry is "birch".
Example 2
Input: str_arr = ["coral", "pearl", "amber", "gem"]
Output: "amber"
Explanation: "coral", "pearl", and "amber" all have 5 letters, outranking "gem" (3). Preserving original order places "coral" 1st, "pearl" 2nd, and "amber" 3rd.
Example 3
Input: str_arr = ["falcon", "hawk", "wren"]
Output: "wren"
Explanation: "falcon" (6) comes 1st, followed by the two 4-letter words "hawk" (2nd) and "wren" (3rd).
Example 4
Input: str_arr = ["sun", "planet", "sky", "galaxy"]
Output: "sun"
Explanation: The two 6-letter words "planet" and "galaxy" fill 1st and 2nd place, followed by the two 3-letter words "sun" (3rd) and "sky" (4th).
Constraints
3 <= len(str_arr) <= 100,000- Every entry in
str_arris a non-empty string composed exclusively of ASCII letters (a-z,A-Z).
Step-by-step walkthrough
Restate the problem and the two tie-breaking rules
We receive a list of at least 3 words
str_arrand must order every word from longest to shortest, then return whichever word sits in 3rd place.Keep two details front and center: 1. 3rd slot, not 3rd distinct length: Every element of
str_arroccupies its own position in the ordered sequence. When three words tie at length5, they fill positions 1, 2, and 3. 2. Equal lengths preserve initial order: Words of identical length are never sorted alphabetically — whichever appeared earlier instr_arrstays ahead.Input: ["coral", "pearl", "amber", "gem"] Lengths: 5 5 5 3 Ordered: Slot 1 Slot 2 Slot 3 Slot 4 "coral" "pearl" "amber" "gem" (len 5, (len 5, (len 5, (len 3) idx 0) idx 1) idx 2) ^ return "amber"Brute force: count how many words outrank each position
We can determine the exact
0-based index (0,1,2, ...) ofstr_arr[i]directly from the rules. Entryjsits ahead of entryiprecisely when either: -len(str_arr[j]) > len(str_arr[i])(entryjhas strictly more characters), or -len(str_arr[j]) == len(str_arr[i])andj < i(identical character count, andjcame earlier).Counting how many indices
jprecede eachilocates the word at0-based slot2:from typing import List def third_largest_brute_force(str_arr: List[str]) -> str: for i in range(len(str_arr)): ahead_count = 0 for j in range(len(str_arr)): is_longer = len(str_arr[j]) > len(str_arr[i]) is_earlier_tie = len(str_arr[j]) == len(str_arr[i]) and j < i if is_longer or is_earlier_tie: ahead_count += 1 if ahead_count == 2: return str_arr[i] return ""This nested loop makes an ideal test oracle on small inputs, though checking all pairs takes
O(n^2)time (10^10comparisons whenn = 100,000).Key idea: stable descending sort by length (and the ascending-sort trap)
A stable sort guarantees that items with equal sort keys remain in the exact relative sequence they had before sorting. Python's built-in
sorted()runs Timsort, which is guaranteed stable — even withreverse=True!Sorting
str_arrwithkey=lenandreverse=Truebuilds our exact target sequence inO(n log n)time, placing the 3rd-place word at0-based index2.Watch out for a common trap: sorting ascending (
reverse=False) and indexing[-3]from the back does not match when lengths tie!Input: ["coral", "pearl", "amber", "gem"] 1. CORRECT: sorted(str_arr, key=len, reverse=True) -> ["coral", "pearl", "amber", "gem"] (ties stay coral, pearl, amber) Index [2] --> "amber" (correct!) 2. BUGGY: sorted(str_arr, key=len) -> ["gem", "coral", "pearl", "amber"] (ascending keeps coral, pearl, amber...) Index [-3] --> "coral" (WRONG! Counting from the back flips tie order!)Reversing after an ascending sort (
sorted(str_arr, key=len)[::-1]) commits the exact same error because[::-1]reverses"coral", "pearl", "amber"into"amber", "pearl", "coral". Passingreverse=Truedirectly tosorted()preserves tie stability.Walk through all four examples
Let's trace
sorted(str_arr, key=len, reverse=True)[2]across Examples 1–4:Example 1: ["maple", "birch", "redwood", "oak"] lengths: 5 5 7 3 ranked: ["redwood", "maple", "birch", "oak"] -> ranked[2] = "birch" Example 2: ["coral", "pearl", "amber", "gem"] lengths: 5 5 5 3 ranked: ["coral", "pearl", "amber", "gem"] -> ranked[2] = "amber" Example 3: ["falcon", "hawk", "wren"] lengths: 6 4 4 ranked: ["falcon", "hawk", "wren"] -> ranked[2] = "wren" Example 4: ["sun", "planet", "sky", "galaxy"] lengths: 3 6 3 6 ranked: ["planet", "galaxy", "sun", "sky"] -> ranked[2] = "sun"Every trace matches its expected output.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def third_largest_word(str_arr: List[str]) -> str: # ranked_words: copy of str_arr ordered from longest word to shortest word. # Python's Timsort is stable even when reverse=True, so equal-length words keep # their original left-to-right input order (unlike sorted(str_arr, key=len)[-3]). ranked_words = sorted(str_arr, key=len, reverse=True) # Return 1-based rank 3 (0-based index 2); valid because len(str_arr) >= 3. return ranked_words[2]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining runners up from tallest to shortest while promising that any two runners of the exact same height keep the order in which they arrived, then handing the bronze medal to the 3rd person in line. Preserving initial arrival order whenever two sort keys tie is the defining guarantee of a stable sort (implemented in Python by Timsort, a hybrid merge-and-insertion sort powering sorted() and list.sort()). Calling sorted(str_arr, key=len, reverse=True) orders strings from longest to shortest while keeping equal-length strings in their initial sequence, so ranked_words[2] immediately returns the 3rd-place word.
Why do other obvious attempts fall short? Comparing every word against every other word to count how many outrank it requires O(n^2) nested loops. Collecting unique lengths in a set fails because the prompt asks for the 3rd entry in the ordered sequence, not the 3rd distinct length (["coral", "pearl", "amber", "gem"] has lengths [5, 5, 5, 3], so all top three entries have length 5). Most subtly, sorting ascending and reading 3rd-from-last (sorted(str_arr, key=len)[-3]) leaves tied words in forward order near the end of the array, so indexing from the right picks the 1st tied word instead of the 3rd!
Here is a 4-word trace of Example 2 showing why reverse=True gets ties right while ascending [-3] flips them:
Input: ["coral", "pearl", "amber", "gem"] (lengths: 5, 5, 5, 3)
sorted(str_arr, key=len, reverse=True):
index: 0 1 2 3
words: ["coral", "pearl", "amber", "gem"] -> index [2] = "amber" (3rd of the 5-letter ties)
sorted(str_arr, key=len):
index: -4 -3 -2 -1
words: [ "gem", "coral", "pearl", "amber"] -> index [-3] = "coral" (wrong: 1st of the ties!)
Complexity
Let n be the number of strings in str_arr (n >= 3).
- Time:
O(n log n). Python strings cache their character count in the object header, solen(word)runs inO(1)time regardless of string length. Timsort performs at mostO(n log n)key comparisons across thenentries (dropping towardO(n)on nearly ordered inputs), followed by oneO(1)lookupranked_words[2]. - Space:
O(n).sorted()allocates a new list holdingnstring references (ranked_words) without duplicating the underlying character buffers.
Edge cases
- Minimum valid size (
n == 3):ranked_wordshas indices0, 1, 2, returning whichever word lands last; when all three share one length (e.g.,["cat", "dog", "owl"]), initial order holds and"owl"wins. - Tie spanning 3rd place: In
["aaaa", "bb", "cc", "dd"],"aaaa"takes 1st (len 4), and the three length-2 words stay"bb", "cc", "dd", placing"cc"in 3rd. - Tie covering all top three positions (Example 2): In
["coral", "pearl", "amber", "gem"], all top three have length5, and"amber"takes 3rd. - Repeated identical words: Duplicates like
["hello", "hello", "hi", "hello"]remain distinct list elements at indices0, 1, 3, so the third"hello"lands in 3rd place. - Mixed uppercase and lowercase letters:
key=lenignores letter case completely, so"Zebra","apple", and"Mango"all tie at length5and retain arrival order.
Common mistakes
- Sorting ascending and taking
[-3]or reversing[::-1]: Bothsorted(str_arr, key=len)[-3]andsorted(str_arr, key=len)[::-1][2]invert tie order, failing Example 2 ("coral"instead of"amber"). - Deduplicating lengths or words: Wrapping inputs in
set(...)drops repeated lengths or duplicate words and raisesIndexErrorwhen fewer than three unique lengths exist (such as["cat", "dog", "owl"]). - Breaking ties alphabetically (
key=lambda w: (-len(w), w)): Including the word text in the key overrides stability and reorders equal-length words alphabetically. - Off-by-one indexing (
ranked_words[3]): Python lists are0-indexed, so 1st place is[0], 2nd is[1], and 3rd is[2].
Alternative approaches
- Single-pass top-3 tracker (
O(n)time,O(1)extra space): Keep a listtopof at most 3 words in current order. For eachwordinstr_arr, insert it right before the first entry intopthat is strictly shorter (len(word) > len(top[k])— strict>ensures equal-length words land after earlier ties!), or append iflen(top) < 3, trimmingtopback to length 3:
def third_largest_one_pass(str_arr):
top = []
for word in str_arr:
insert_at = len(top)
for k in range(len(top)):
if len(word) > len(top[k]):
insert_at = k
break
if insert_at < 3:
top.insert(insert_at, word)
if len(top) > 3:
top.pop()
return top[2]
heapq.nlargest(3, str_arr, key=len)[2]: Python'sheapq.nlargest(k, iterable, key=len)is documented to matchsorted(iterable, key=key, reverse=True)[:k](including tie stability) inO(n log 3) = O(n)time andO(1)auxiliary space.
Follow-up questions
- How would you generalize this function to find the k-th longest word for an arbitrary integer k? Check
1 <= k <= len(str_arr)first. Whenkis close ton,sorted(str_arr, key=len, reverse=True)[k - 1]runs inO(n log n)time. Whenkis much smaller thann, maintain a size-kmin-heap (a binary tree stored in an array whose smallest entry sits at index0and updates inO(log k)time) holding(len(word), -index, word): negating-indexmakes a later equal-length word compare smaller than an earlier one so later ties are evicted first, leaving the topkwords inO(n log k)time andO(k)space. - If words arrived one by one from a huge stream that could not fit in RAM, how would you compute the answer in a single pass? Run the single-pass top-3 tracker above (or the size-
kmin-heap for arbitraryk): each arriving string is inspected once, non-qualifying strings are discarded immediately, auxiliary memory staysO(1), andtop[2]holds the live 3rd-longest word at every point from the 3rd item onward. - How would your sort key change if equal-length ties had to be broken in case-insensitive alphabetical order before falling back to input position? Pass a tuple key
key=lambda w: (-len(w), w.lower())tosorted(str_arr)(withoutreverse=True):-len(w)places longer strings first,w.lower()orders equal-length strings alphabetically ignoring case ("apple"before"Mango"), and Timsort's stability still breaks identical case-folded ties (such as"Apple"vs."apple") by initial input position.
Follow-up questions
- How would you generalize this function to find the k-th longest word for an arbitrary integer k?
- If words arrived one by one from a huge stream that could not fit in RAM, how would you compute the answer in a single pass?
- How would your sort key change if equal-length ties had to be broken in case-insensitive alphabetical order before falling back to input position?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array