Minimum number of palindromes required to express N as a sum | Set 2
Given a number N, we have to find the minimum number of palindromes required to express N as a sum of them.
Input : N = 11
Output : 1
Explanation: 11 is itself a palindrome.
Input : N = 65
Output : 3
Explanation: 65 can be expressed as a sum of three palindromes (55, 9, 1).
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 the previous post, we discussed a dynamic programming approach to this problem which had a time and space complexity of O(N3/2).
Cilleruelo, Luca, and Baxter proved in a 2016 research paper that every number can be expressed as the sum of a maximum of three palindromes in any base b >= 5 (this lower bound was later improved to 3). For the proof of this theorem, please refer to the original paper. We can make the use of this theorem by safely assuming the answer to be three if the number N is not itself a palindrome and cannot be expressed as the sum of two palindromes.
Below is the implementation of the above approach:
Time Complexity: O(√(N)log N).