From Brute Force to Optimal: Level Up Your Solutions Like a Zelda Speedrun
The Quest Begins (The "Why") Ever felt like you’re stuck grinding the same low‑level enemies over and over, just waiting for that sweet XP boost? I’ve been there. A few weeks ago I was tackling the classic Two Sum interview problem: given an array of integers and a target, return the indices of the two numbers that add up to the target. My first instinct? Bash out a double loop, check every pair,…
The story begins with a common struggle—stuck on low-level problems like the Two Sum interview question. The initial brute force approach uses a double loop with O(n²) time complexity, which becomes slow with large inputs. The turning point comes when the author realizes they are repeatedly asking "What number do I need to pair with the current one to hit the target?"
Instead of scanning the array for each element, the author proposes remembering previously seen numbers using a hash map (dictionary) that maps values to their indices. This allows checking whether the needed complement already exists in O(1) time. The trade-off is O(n) space for the hash map, but this is often outweighed by the drastic reduction in time complexity.
A buggy version is shown that stores the complement instead of the actual value, leading to failures with duplicate numbers. The article then presents a polished solution that correctly stores the seen number and returns the indices once the complement is found. Common pitfalls like overwriting indices or ignoring negative numbers are highlighted, along with test cases demonstrating the solution's correctness.
The author emphasizes that this hash-based lookup approach is not just about passing interviews, but also about changing one's problem-solving mindset to view challenges as lookup queries rather than brute-force enumerations. This mindset enables tackling a wider range of problems efficiently, leading to faster code, less interview anxiety, and the ability to focus on higher-stakes aspects like system design.
The story concludes by inviting readers to identify their own brute-force problems and apply the "look for the complement" insight to find clever optimizations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.