Recursion or Dynamic Programming?
A candidate attended the interview after practicing a lot of puzzles and algorithms. He cleared all the interview rounds easily and joined the job as a Developer.
Client: I am constructing a multistoried apartment. Floors are numbered a bit differently. The first floor is numbered as 0, the 2nd floor is numbered as 1, the 3rd floor is numbered as 2, and so on. I need an application that can give me the floor number for the given n value.
The product manager shared client requirements with the team and the new developer was assigned to develop a solution.
Developer: This problem sounds like f(n) = f(n-1) + 1. So it can be solved using recursion
The developer wrote the following code and went to the Lead for review.
int getNthNumber(int n) {
if (n == 1) {
return 0
} else {
return getNthNumber(n - 1) + 1
}
}
Lead: Code looks good. But recursion is inefficient in terms of space as it adds up memory to stack for each call. Solve it iteratively using Dynamic Programming / Memoization.
Developer considered Lead’s feedback and solved it iteratively
int getNthNumber(int n) {
int result = -1
for (int i = 1; i <= n; i++) {
result = result + 1
}
return result
}
Lead: Code looks good, let us deliver to the client.
The client was happy that the app is working, but felt that the app is taking a long time for larger numbers and shared feedback with the team.
The team had a Tech Debt and after a long discussion, they realized that this problem does not need Recursion or Dynamic Programming and came up with the following solution.
int getNthNumber(int n) {
return n - 1
}
Simplicity is the ultimate sophistication
Did you ever come across an Over Engineering trap in your career?