Not sure how to solve an algorithms problem? Here are some techniques you could try:
Solve it Manually
Try to solve the problem manually with some simple data and then see if you can derive an algorithm from that process. For example, you could probably discover the insertion sort or selection sort algorithms by trying to sort an a list of numbers on your own.
3 1 9 5 7 11 13 6 8
Break it Down
"Divide and conquer"
Solve a smaller part or an easier version of the problem and then work to conquer the entire problem. Many problems are naturally solved by solving one piece at a time, but sometimes you need to figure out how the problem can be simplified.
For example, Manhattan Meeting Place asked to find the meeting place on a grid that would minimize the total travel distance of all parties. You could start by answering the question for a single 1D-road before moving on to a grid. See this blog post for further explanation. (Check out many of the challenges on Learneroo to see how large challenges can be broken down into smaller problems.)
Search through common Data Structures and Algorithms that you know and see if any of them could be "plugged-in" to solve the problem. It's a "Solution Looking for a Problem", but it can work! For example, if you are asked to find the shortest path by number of nodes between 2 points on a graph, go through the graph-search algorithms to see what would solve that problem. (See the Subway app challenge to practice a very similar challenge.)
Suspect a problem can be solved with Recursion? See the Recursion review for some tips. Practice 2 of these approaches with the basic challenge below.
The interviewer has another challenge for you:
Given a list of numbers can you find all the pairs of numbers whose sum equals
For example, when given the list
1 9 11 13 2 3 7 5and
12, you should find these pairs:
Before clicking below, think about how you would solve this problem manually and how to convert the solution to code.
This is a simple problem, and even comes with an example input.
- Start at the first number in the list
11, which would create a 12-pair
scan through every number to the right to see if you find an
- Then move on the next number
9and repeat the process, scanning to the right of
- Repeat this process for the entire list.
This solution can easily be converted into code that uses 2
for loops to go through the list.
Interviewer: That solution is OK, but can you find a more optimal one?
Interviewer: Yes, that data structure will be useful, can you spell out the solution?
Interviewer: OK, that algorithm will work. Now can you write the code?
Go to More Hashing Practice to write your code for this challenge!