- Keep your implementation as simple as possible
- Knowing the basics of time and space complexity goes a long way.
- Additional Tip: Always use parent interface for the type
- When trying to find duplicates
- Java: If you know the size of the list
- Always have your algorithmic logic in a separate function
- Rather than implementing own logic, take 5 minutes to see if your modules already provide the implementation
If you are inventing new algorithms, you either don’t know the right algorithm or are working on your PhD thesis.
Eliminating as much of this accidental complexity as possible.
Keep your implementation as simple as possible
If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea.
~ The Zen of Python, by Tim Peters
Knowing the basics of time and space complexity goes a long way.
Going through each is beyond the scope of this. Here is a link if you want to go in-depth: Cracking the Coding Interview YouTube
The concept of List, Sets, and Maps is universal though this particular post is going to look at it through the lens of Java. In the case of Python map is called a dictionary.
Additional Tip: Always use parent interface for the type
Be as general as you can be.
This allows you to swap in any form of implementation of parent interface in a single line.
When trying to find duplicates
Use Set instead of Lists
Set always contain unique values.
Finding an element in the set is much faster O(1) than compared to a list O(n)
Java: If you know the size of the list
… if the required maximum capacity of the ArrayList is known, we can get the optimal performance (both average latency and throughput) by specifying the initial capacity to the required capacity.
In doing so, we can get 24% to 34% improvement in average latency and 30% to 50% improvement in throughput.
Always have your algorithmic logic in a separate function
This just makes it much easier to debug. Your function will be doing just one this.
Making it general enough will be even helpful so that you can easily use it.
Rather than implementing own logic, take 5 minutes to see if your modules already provide the implementation
A library in java which you can find is Apache Common Lang 3 which does provide a lot of utilities.
Python has much more abundance. Just google a solution for python and you will probably find a pip package.
Previous: Remove unnecessary code
Index: Tips on writing Clean Code