Given a number N and a digit D, we have to form an expression or equation that contains only D and that expression evaluates to N. Allowed operators in an expression are +, -, *, and / . Find the minimum length expression that satisfies the condition above and D can only appear in the expression at most 10(limit) times. Hence limit the values of N (Although the value of limit depends upon how far you want to go. But a large value of limit can take a longer time for the below approach).
Remember, there can be more than one minimum expression of D that evaluates to N but the length of that expression will be minimum.
Input : N = 7, D = 3 Output : 3/3+ 3 + 3 Explanation : 3/3 = 1, and 1+3+3 = 7 This is the minimum expression. Input : N = 7, D = 4 Output : (4+4+4)/4 + 4 Explanation : (4+4+4) = 12, and 12/4 = 3 and 3+4 = 7 Also this is the minimum expression. Although you may find another expression but that expression can have only five 4's Input : N = 200, D = 9 Output : Expression not found! Explanation : Not possible within 10 digits.
The approach we use is Backtracking. We start with the given Digit D and start multiplying, adding, subtracting, and dividing if possible. This process is done until we find the total as N or we reach the end and we backtrack to start another path. To find the minimum expression, we find the minimum level of the recursive tree. And then apply our backtracking algorithm.
Let’s say N = 7, D = 3
The above approach is exponential. At every level, we recurse 4 more ways (at-most). So, we can say the time complexity of the method is where n is the number of levels in the recursive tree (or we can say the number of times we want D to appear at-most in the expression which in our case is 10).
Note: We use the above approach two times. First to find the minimum level and then to find the expression that is possible at that level. So, we have two passes in this approach. We can get the expression in one go, but you’ll need to scratch your head for that.
Expression: (4+4+4)/4+4 Expression: (((7+7)*7)*7+7+7)/7 Expression not found!
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live