I need your help. Could you help me please.
Input: Array A with n natural numbers.
count = 0
for each subset S of 4 elements of A do:
sum = "sumFormula" from i = 0 to 3 S[i]
for i from 0 to n-1 do:
if sum == A[i]:
count = count+1
return count.
I didn't understand it. What time does it take?
My idea: I think it has exponential runtime, because when I double the input size it squares. But I am not sure.
A lot of the complexity of the algorithm is hidden.
In particular:
for each subset S of 4 elements in A
How are these subsets determined?
There are 2^n possible subsets of a set with n elements.
Simply that first step might be the cause of the exponential runtime.
The remainder of the algorithm is essentially figuring out the sum of each of those subsets. That won't affect runtime much.
Related
I already know how to calculate the median, mean, mode from an array in Java. But is there actually a way to do the reverse like creating an array from the median, mode, mean, given the range and the number of numbers in the array ?
The numbers in the array can be created by randomness as long as it satisfies the condition above. It can stop when successfully find the first array with that condition. And plus the range can be from 0 to 10 or 0 to 100, not so much.
Yes / No
When you do an array to mmm, you are applying a lossy algorithm, you are losing the original data.
There can be literally an infinite number of array combinations that would result in the same mmm.
Some naive ideas
Median: for example your array have 2n+1 elements, put n elements which are less than your median, n elements which are greater than median;
Mean: say your array have m elements, Sum = m * Mean, generate m elements by partitioning Sum;
Mode: count the frequency of the numbers you put into the array, make sure Mode has the highest frequency;
Hi I am trying to solve this problem from IEEEXtreme 2014:
You are given N integers that are arranged circularly. There are N ways to pick consecutive subsequences of length M (M < N). For any such subsequence we can find the “K”-value of that subsequence. “K”-value for a given subsequence is the K-th smallest number in that subsequence. Given the array of N, find the smallest K-value of all possible subsequences. For example N=5 M=3 K=2 and the array 1 5 3 4 2 give the result 2.
My approach is first I create a sorted array list which inserts the new input in the correct position. I add the first M integers into the list. Record the K-th smallest value. Then I keep removing the oldest integer and adding the next integer into the list and comparing the new K-th value with the old one. This is my sorted array list.
class SortedArrayList extends ArrayList {
public void insertSorted(int value) {
for (int i = size()-1; i >= 0; i--){
if( value - (Integer)get(i)>=0){
add(i+1,new Integer(value));
return;
}
}
add(0,new Integer(value));
}
}
I think this brute-force method is not efficient but not able to come up with any ideas yet. Do you know any better solutions for this ? Thanks.
Here is a more efficient solution:
Let's get rid of circularity to keep things simpler. We can do it by appending the given array to itself.
We can assume that all numbers in the input are unique. If it is not the case, we may use a pair (element, position) instead of each element.
Let's sort the given array. Now we will use the binary search over the answer(that is, the position of the k-th smallest element among all subarrays in the sorted global array).
How to check that a fixed candidate x is at least as large as the k-th smallest number? Let's mark all positions of the numbers less than or equal to x with 1 and the rest with 0. Now we just need to check if there is a subarray of length M that contains at least k ones. We can do it in linear time using rolling sums.
The time complexity is: O(N log N) for sorting the input + O(N log N) for binary search over the answer(there are O(log N) checks and each of them is done in linear time as described in 4.). Thus, the total time complexity is O(N log N).
P.S. I can think of several other solutions with the same time complexity, but this one seems to be the simplest one to implement(it does not require any custom data structures).
More elegant solution for the problem with the circular array would be to simply use modulo. So, if you're just looking for a solution for simulating a circular array, i would suggest something like this:
int n = somevalue;//the startingpoint of the subsequence
int m = someothervalue;//the index in the subsequence
int absolute_index = (n + m) % N;
where N is the total number of elements in the sequence.
Next step towards more efficiency would be to store the index of the k-th value. This way, you'd only have to calculate a new K-Value every M-th step (worst case) and simply compare it to one new value per every other step.
But i'll leave that to you ;)
public static void Comp(int n)
{
int count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=1;k<n;k*=2)
{
count++;
}
}
}
System.out.println(count);
}
Does anyone knows what the time complexity is?
And what is the Big Oh()
Please can u explain this to me, step by step?
Whoever gave you this problem is almost certainly looking for the answer n^2 log(n), for reasons explained by others.
However the question doesn't really make any sense. If n > 2^30, k will overflow, making the inner loop infinite.
Even if we treat this problem as being completely theoretical, and assume n, k and count aren't Java ints, but some theoretical integer type, the answer n^2 log n assumes that the operations ++ and *= have constant time complexity, no matter how many bits are needed to represent the integers. This assumption isn't really valid.
Update
It has been pointed out to me in the comments below that, based on the way the hardware works, it is reasonable to assume that ++, *=2 and < all have constant time complexity, no matter how many bits are required. This invalidates the third paragraph of my answer.
In theory this is O(n^2 * log(n)).
Each of two outer loops is O(n) and the inner one is O(log(n)), because log base 2 of n is the number of times which you have to divide n by 2 to get 1.
Also this is a strict bound, i.e the code is also Θ(n^2 * log(n))
The time complexity is O(n^2 log n). Why? each for-loop is a function of n. And you have to multiply by n for each for loop; except the inner loop which grows as log n. why? for each iteration k is multiplied by 2. Think of merge sort or binary search trees.
details
for the first two loops: summation of 1 from 0 to n, which is n+1 and so the first two loops give (n+1)*(n+1)= n^2+2n+1= O(n^2)
for the k loop, we have k growing as 1,2,4,8,16,32,... so that 2^k = n. Take the log of both sides and you get k=log n
Again, not clear?
So if we set m=0, and a=2 then we get -2^n/-1 why is a=2? because that is the a value for which the series yields 2,4,8,16,...2^k
Question: Given a sorted array A find all possible difference of elements from A.
My solution:
for (int i=0; i<n-1; ++i) {
for (int j=i+1; j<n; ++j) {
System.out.println(Math.abs(ai-aj));
}
}
Sure, it's O(n^2), but I don't over count things at all. I looked online and I found this: http://www.careercup.com/question?id=9111881. It says you can't do better, but at an interview I was told you can do O(n). Which is right?
A first thought is that you aren't using the fact that the array is sorted. Let's assume it's in increasing order (decreasing can be handled analogously).
We can also use the fact that the differences telescope (i>j):
a_i - a_j = (a_i - a_(i-1)) + (a_(i-1) - a_(i-2)) + ... + (a_(j+1) - a_j)
Now build a new sequence, call it s, that has the simple difference, meaning (a_i - a_(i-1)). This takes only one pass (O(n)) to do, and you may as well skip over repeats, meaning skip a_i if a_i = a_(i+1).
All possible differences a_i-a_j with i>j are of the form s_i + s_(i+1) + ... + s_(j+1). So maybe if you count that as having found them, then you did it in O(n) time. To print them, however, may take as many as n(n-1)/2 calls, and that's definitely O(n^2).
For example for an array with the elements {21, 22, ..., 2n} there are n⋅(n-1)/2 possible differences, and no two of them are equal. So there are O(n2) differences.
Since you have to enumerate all of them, you also need at least O(n2) time.
sorted or unsorted doesn't matter, if you have to calculate each difference there is no way to do it in less then n^2,
the question was asked wrong, or you just do O(n) and then print 42 the other N times :D
You can get another counter-example by assuming the array contents are random integers before sorting. Then the chance that two differences, Ai - Aj vs Ak - Al, or even Ai - Aj vs Aj - Ak, are the same is too small for there to be only O(n) distinct differences Ai - Aj.
Given that, the question to your interviewer is to explain the special circumstances that allow an O(n) solution. One possibility is that the array values are all numbers in the range 0..n, because in this case the maximum absolute difference is only n.
I can do this in O(n lg n) but not O(n). Represent the array contents by an array of size n+1 with element i set to 1 where there is a value i in the array. Then use FFT to convolve the array with itself - there is a difference Ai - Aj = k where the kth element of the convolution is non-zero.
If the interviewer is fond of theoretical games, perhaps he was thinking of using a table of inputs and results? Any problem with a limit on the size of the input, and that has a known solution, can be solved by table lookup. Given that you have first created and stored that table, which might be large.
So if the array size is limited, the problem can be solved by table lookup, which (given some assumptions) can even be done in constant time. Granted, even for a maximum array size of two (assuming 32-bit integers) the table will not fit in a normal computer's memory, or on the disks. For larger max sizes of the array, you're into "won't fit in the known universe" size. But, theoretically, it can be done.
(But in reality, I think that Jens Gustedt's comment is more likely.)
Yes you can surely do that its a little tricky method.
to find differances in O(n) you will need to use BitSet(C++) or any similar Data Structure in respective language.
Initialize two bitset say A and B
You can do as follows:
For each iteration through array:
1--store consecutive differance in BitSet A
2--LeftShift B
3--store consecutive differance in BitSet B
4--take A=A or B
for example I have given code-
Here N is Size of array
for (int i=1;i<N;i++){
int diff = arr[i]-arr[i-1];
A[diff]=1;
B<<=diff;
B[diff]=1;
A=A | B;
}
Bits in A which are 1 will be the differances.
First of all the array need to be sorted
lets think a sorted array ar = {1,2,3,4}
so what we were doing at the O(n^2)
for(int i=0; i<n; i++)
for(int j=i+1; j<n; j++) sum+=abs(ar[i]-ar[j]);
if we do the operations here elaborately then it will look like below
when i = 0 | sum = sum + {(2-1)+(3-1)+(4-1)}
when i = 1 | sum = sum + {(3-2)+(4-2)}
when i = 2 | sum = sum + {(4-3)}
if we write them all
sum = ( -1-1-1) + (2+ -2-2) + (3+3 -3) + (4+4+4 )
we can see that
the number at index 0 is added to the sum for 0 time and substracted from the sum for 3 time.
the number at index 1 is added to the sum for 1 time and substracted from the sum for 2 time.
the number at index 2 is added to the sum for 2 time and substracted from the sum for 1 time.
the number at index 3 is added to the sum for 3 time and substracted from the sum for 0 time.
so for we can say that,
the number at index i will be added to the sum for i time
and will be substracted from the sum for (n-i)-1 time
Then the generalized expression for
each element will be
sum = sum + (i*a[i]) – ((n-i)-1)*a[i];
I have two list of numbers, for every member of the second one I must tell if it's obtainable using all the numbers of the first one and placing '+' or '*' and as many '(' ')' I want.
I can't change the order .
List1 can contain a max of 20 elements beetween 1 and 100.
List2 can contain max 5 elements beetween 1 and 20'000.
EX:
List1=[2 4 3 5]
List2=[19 15 24]
19-> 2+(4*3)+5 YES
15 NO
24->2*(4+3+5) YES
With brute force it takes ages to handle inputs with List1 larger than 10.
edit: numbers are always positive.
edit:
I find the max and min numbers that are obtainable from the list and then I discard all the possibilities that have the target outside this range, then I try all the remaining ones.
MAX=n1*n2*n3*....*ni if there are 1 thei r added to their smallest neighbour
MIN=n1+n2+....+ni 1 excluded
Still it's not fast enough when input are big (List1 longer than 10 or numbers in List2 bigger than 10000)
For each sublist of List1, compute the numbers between 1 and 20,000 that can be made with that sublist. The resulting DP bears resemblance to CYK.
I'm being somewhat vague here because this is almost certainly a programming contest problem.
#u mad is correct, but I'll give a little more detail.
Suppose that n = size of list 1. For each 0 <= i < j < n you need to compute all of the distinct values in the range (1..20_000) that can be made from the numbers in the interval [i, j-1]. You can do this with recursion and memoization.
Once you've done this then the problem is easy.
You could try a smart brute force which discards sets of equations by chunks.