Algorithms and problem-solvingmedium3-5 years

Someone writes a 'find the second-largest number' function by sorting the whole list and reading off the second element. It works, it passes every test with a small array, and it's noticeably slow once the list has a million entries. What's actually wrong with the approach, and separately — what's the general mistake in assuming the machine will 'figure out' what you meant for an input you didn't think about, like an empty list?

Two separate things, both real. First, cost: sorting the whole list to find one value does more work than the question needs — sorting is roughly O(n log n) comparisons, but tracking the largest and second-largest in a single pass is O(n), and at a million elements that's the difference between milliseconds and something you actually notice. Second, correctness on edge cases: a one-element list has no second-largest, and [5, 5, 3] is ambiguous — is the second-largest 5 or 3? The machine won't fill in an answer that 'feels right' to a human; if the algorithm doesn't say what to do, it either crashes or silently returns something wrong, and either way that's a decision the person writing it skipped, not one the computer made for them.

The lesson behind it →