LendingKart Interview Question
SDE-2sCountry: India
Solution using recursive program
public static void main(String[] args) {
int n = 51, k = 3;
StringBuilder sb = new StringBuilder();
find(n, k, sb);
}
private static void find(int n, int k, StringBuilder sb ){
if(n < k || 26 * k < n) return ;
if(n-26>k){
sb.append( "z" );
n = n-26;
k--;
find( n,k,sb );
}else{
sb.append( (char)((int)'a'+n-k));
if(k>1) {
k--;
if(k>n-26){
n = k;
}else{
n = n-26;
}
find( n, k , sb );
}else{
System.out.println( sb.reverse().toString() );
}
}
return;
}
public static void main(String[] args) {
int n = 51, k = 3;
StringBuilder sb = new StringBuilder();
find(n, k, sb);
}
private static void find(int n, int k, StringBuilder sb ){
if(n < k || 26 * k < n) return ;
if(n-26>k){
sb.append( "z" );
n = n-26;
k--;
find( n,k,sb );
}else{
sb.append( (char)((int)'a'+n-k));
if(k>1) {
k--;
if(k>n-26){
n = k;
}else{
n = n-26;
}
find( n, k , sb );
}else{
System.out.println( sb.reverse().toString() );
}
}
return;
}
Hi Acharya,
Your problem can be solved in two approaches.
If I were in an interview, I will start with the most basic brute force thing,
which means I will find out all permutations of characters which give me this.
So the recurrence will be
find(n,k, "") = f(n-1, k - 1, "a") or f(n - 2, k - 1, "b") or f(n - 3, k - 1, "c") .. or f(n - 26, k - 1, "z")
which will recur like
find(n - 1, k - 1, "a") = f(n - 2, k - 2, "aa") or f(n - 3, k - 2, "ab") ... or f(n - 26, k - 2, "az")
the exit condition will be
when n == 0 and k == 0 then we set a global string with the current value
or n== 0 && k > 0 no solution possible
or n > 0 && k == 0 no solution possible
Note that we can only set the global string when it is empty and that will provide us the lexicographical smallest string with length k and sum n.
But this will be recurring for all n positions and in total will be order of 26*26*26...*26(k times)
i.e. O(26^k) which is exponential and bad for the computation.
The quicker approach can be done in greedy way in O(n)
For this approach note that if we can choose the last position as the maximum possible value such that we can still fill the rest of the positions with 1's i.e. a
so zaaaaaa should be feasible or else we will try with yaaaaa etc.
at each position we will try this and maintain the same rule throughout
at the end of this process we will get a string of length k and sum as n and we will reverse it.
But this will also be the lexicographical smallest string on reversing since
the sum is distributed in such a way that the end positions got the maximum that they can.
Regards,
- Shubham Awasthi August 21, 2019Shubham