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.
PreviousA method's local variable disappears the instant the method returns, but an object created inside that same method can still be alive minutes later. Why do these two things, created in the same line of code, have such different lifetimes?Next A mobile client times out waiting for a response to `POST /api/orders`, so it automatically retries the exact same request. What could go wrong, and would the same retry be safe for `PUT /api/orders/42`?