Ninjas are often known for their will to never give up no matter how fierce the challenge. One such ninja was challenged by another if they could solve a problem to find the Kth number in a list of given elements (array) comprising of only 3, 5 and 7 as their prime factors. Despite the ninja’s strong will to solve the problem, you know that it could be easily solved with the help of knowledge of programming. Since the ninja does not know that you’ll have to devise an algorithm for solving the problem. Your task is to complete the given function which returns that required Kth element from the array.
For Example:Input: 'K' = 10
Output: 45
The array will contain elements that only have 3, 5 or 7 as their prime factors i.e. of the following form:- 3,5,7,9,15,21,25,…. Therefore we can see from the above pattern of elements that 45 would be the 10th element in the array which is our required answer.
The first line of input contains an integer ‘T’ denoting the number of test cases to run.
Then the test cases follow:-
The first and the only line of each test contains an integer 'K', denoting the Kth number that we want.
Output format:
For each test case, return the Kth element from the array.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= K <= 3 * 10^3
Time limit: 1 second
3
9
5
10
35
15
45
The array will contain elements that only have 3, 5 or 7 as their prime factors i.e. of the following form:- 3,5,7,9,15,21,25,27,35,45….
Therefore we can see from the above pattern of elements that the 9th, 5th and 10th elements would be 35, 15 and 45 respectively.
2
12
8
63
27
Can we find the minimum value which would be next in the sequence to solve this problem?
The key observation here is to notice a simple fact that the Kth element would always be of the form:-
Kth Multiple of 3, 5 and 7 = 3k * 5k * 7k
We can simply iterate through from 1 to ‘k-1’ and Initialize three queues say Q3, Q5, Q7 and an integer variable say ‘X’ = 1. Keep track of the minimum element among the queues and make that the next value of ‘X’ in our array.
The algorithm for the same can be as follows:-
O(K), where ‘K’ is the number that is required from the array.
Now, since there are K iterations in total. So the time complexity grows by O(K).
O(1),
Constant space is used.