Have you ever given a programming problem and freeze without knowing where to start? Well, in this section, we are going to give some tips so you don’t get stuck while coding.
Tip
|
TL;DR: Don’t start coding right away. First, solve the problem, then write the code. Make it work first; make it better later. |
-
Understand the requirements. Reframe it in your own words.
-
Draw a simple example (no edge cases yet)
-
Brainstorm possible solutions
-
How would you solve this problem manually? (without a computer) Is there any formula or theorem you can use?
-
Is there any heuristics (largest, smallest, best ratio), or can you spot a pattern to solve this problem using a greedy algorithm?
-
Can you address the simple base case and generalize for other cases using a recursive solution? Can you divide the problem into subproblems? Try [Divide and Conquer].
-
Do you have to generate multiple solutions or try different paths? Try [Backtracking].
-
List all the data structures that you know that might solve this problem.
-
If anything else fails, how would you solve it the dumbest way possible (brute force). We can optimize it later.
-
-
Test your algorithm idea with multiple examples
-
Optimize the solution –Only optimize when you have something working. Don’t try to do both at the same time!
-
Can you trade-off space for speed? Use a [hashmap-chap] to speed up results!
-
Do you have a bunch of recursive and overlapping problems? Try [dynamic-programming-chap].
-
Re-read requirements and see if you can take advantage of anything. E.g. is the array sorted?
-
-
Write Code, yes, now you can code.
-
Modularize your code with functions (don’t do it all in one giant function, please 🙏)
-
Comment down edge cases but don’t address until the basic cases are working.
-
-
Test your code.
-
Choose a typical input and test against your code.
-
Brainstorm about edge cases (empty, null values, overflows, largest supported inputs)
-
How would your code scale beyond the current boundaries?
-
These steps should get you going even with the most challenging algorithmic problems.
Stay effective!