# Avoid inventing algorithms and data structures

especially for maths

- 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

Ifyou areinventing new algorithms, you eitherdon’t knowthe right algorithmorare working on yourPhDthesis.

Eliminatingas much of thisaccidental complexityas possible.

Source: Why Your Code Is So Hard to Understand

## 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.

Source: Performance Evaluation of Java ArrayLists

## 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.

**Example:** *Separate loop and operation section: Clean Code #1*

## Rather than implementing own logic, take 5 minutes to see if your modules already provide the implementation

### Example: Sorting in Javascript/Typescript

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

**Next**: Always know why you are catching an exception

**Index**: Tips on writing Clean Code