## LendingKart Interview Question

SDE-2s**Country:**India

```
public class BeautifulNumberWith4And5 {
private static String getBeautifulNumber(int n) {
String s = "";
LinkedList<String> l = new LinkedList<>();
l.add("");
while (true) {
String i = l.remove();
l.add(i + "4");
n--;
if (n == 0) {
return i + "4" + new StringBuilder(i + "4").reverse();
}
l.add(i + "5");
n--;
if (n == 0) {
return i + "5" + new StringBuilder(i + "5").reverse();
}
}
}
public static void main(String[] args) {
System.out.println(getBeautifulNumber(1));
System.out.println(getBeautifulNumber(2));
System.out.println(getBeautifulNumber(3));
System.out.println(getBeautifulNumber(4));
}
}
```

Generate n the number using 4,5 now concatenate the number of it's reverse.

Hi Acharya,

This is to calculate the next number, just like after 1 comes 2, after 2 comes 3 and so on.

Only difference is that you need to increase the middle element first to find the next number i.e. for 455554 next number is 544445.

So we started from middle and went till we got a number which is 4, and we convert it to 5 and again go till middle and set everything to 4. i.e. 455554->555555->544445

(Now to make sense of it in our decimal number system.

9899->9999->9900)

What about the case when we have all 5 then we need to add 4 to beginning and end and keep everything else as 4 i.e. 5555->455554->444444

(Similar to our decimal system 9999->19999->10000)

Below is the code:

The complexity is n*(time taken to generate the next item, which is proportional to the string length)

( 2 + 2 + 4 + 4 + 4 + 4 + 8 + 8 + 8 + 8.. + (n / log(n))) n times

let's convert every string length to n so this will be proportional to O(n^2)

Regards,

- yesshubham August 21, 2019Shubham