A friend of mine is interviewing for a job. One of the interview questions got me thinking, just wanted some feedback.
There are 2 non-negative integers: i and j. Gi
My Intuition :
If I take initial value as 1 where i=0, j=0, then I can create next numbers as (2^1)(5^0), (2^2)(5^0), (2^0)*(5^1), ... i.e 2,4,5 ..
Let say at any point my number is x. then I can create next numbers in the following ways :
Explanation :
Since new numbers can only be the product with 2 or 5.
But 4 (pow(2,2)) is smaller than 5, and also we have to generate
Numbers in sorted order.Therefore we will consider next numbers
be multiplied with 2,4,5.
Why we have taken x*4 ? Reason is to pace up i, such that it should not
be greater than pace of j(which is 5 to power). It means I will
multiply my number by 2, then by 4(since 4 < 5), and then by 5
to get the next three numbers in sorted order.
Test Run
We need to take an Array-list of Integers, let say Arr.
Also put our elements in Array List Arr.
Initially it contains Arr : [1]
Lets start with x = 1.
Next three numbers are 1*2, 1*4, 1*5 [2,4,5]; Arr[1,2,4,5]
Now x = 2
Next three numbers are [4,8,10] {Since 4 already occurred we will ignore it} [8,10]; Arr[1,2,4,5,8,10]
Now x =4
Next three numbers [8,16,20] {8 already occurred ignore it} [16,20] Arr[1,2,4,5,8,10,16,20]
x = 5
Next three numbers [10,20,25] {10,20} already so [25] is added Arr[1,2,4,5,8,10,16,20,25]
Termination Condition
Terminating condition when Arr last number becomes greater
than (5^m1 * 2^m2), where m1,m2 are given by user.
Analysis
Time Complexity : O(K) : where k is numbers possible between i,j=0 to
i=m1,j=m2.
Space Complexity : O(K)