How to Optimize With Patterns and Abstractions
After you've done about ~50-100 practice interview challenges, you'll begin to recognize patterns you can leverage. Here's an example of one: If you want speed, you usually need more space/memory.
This is especially relevant to the next section about using a data structure.
Look at each step in your solution so far and think about any potential ways to simplify it or break it down. Are there any ways to reduce its complexity?
One trick is to think about what you're doing from a higher-level. By this, I mean get yourself out of the weeds of the logic, and go back to input-to-output. In the above example, yes we're moving zeros to the end by concatenating arrays, but what are the actual things we'll need to do? The process might be thought of as:
- Identify the non-zero elements
- Put elements at different indexes
- Find out how many
0
s there are
The beauty of having clear steps like the above is that you can now explore alternative ways to accomplish each one.
- For example, to identify the non-zero elements, you can iterate over the array and use a conditional.
- Alternatively, you can use a
filter
method. - And if that's not helpful, you can also look for multiple
zeros
in a row andsplice
a new array out.
Something else to ask yourself: What am I trying to do in plain English?
Another very easy way to make progress is to try to futz with the input.
- If it's a collection, does sorting or grouping help?
- If it's a tree, can we transform it into an array or a linked list?

If tweaking the input doesn't make a dent, maybe it's time to make a bigger transformation.