Read the problem before you type
Most failed coding rounds fail in the first two minutes: the candidate starts typing before they know what is being asked. The fix is a fixed routine you run every time, out loud in an interview and in a comment block at home.
- 1Restate it
Say the problem back in one sentence of your own. "Given a list of prices, return the biggest profit from one buy followed by one later sell."
- 2Pin down input and output
Types, sizes and ranges.
List<Int>orIntArray? Can it be empty? Negative numbers? ReturnInt,Int?or throw? In Kotlin, deciding whether "no answer" isnullis part of the design. - 3Write three examples by hand
A normal case, an edge case (empty, one element, all equal) and a tricky case (the answer is at the very end, duplicates). Work each out on paper — these become your tests.
- 4Brute force first
Say the obvious solution and its cost, even if it is O(n²). It proves you understand the problem and gives you something to check the fast version against.
- 5Name the pattern, then optimise
Sorted input? Two pointers or binary search. "Longest/shortest contiguous…"? Sliding window. "Have I seen this before?" Hash map. Nested structure or "most recent"? Stack. "All combinations"? Backtracking. Grid or network? BFS/DFS. "How many ways / best value" with overlapping sub-problems? DP.
- 6Test with the small cases
Run your three examples, then trace one by hand. Only then talk about further optimisation.
