Given an array of size N, there exist a pattern such that, a[i]-M <= a[i+1] <= a[i]+M . Suggest an algorithm to search for a number in the given array. The solution should be better than O(n).
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Given an array of size N, there exist a pattern such that, a[i]-M <= a[i+1] <= a[i]+M . Suggest an algorithm to search for a number in the given array. The solution should be better than O(n).
Name |
---|
Are you sure it's supposed to be better than O(n) even when the array would be full of repeated 4 and 2 (I mean, 4 2 4 2 4 2 4 2 .....) and in the middle would be 3 and you had to find it?
Sorry without repetition.Please tell your approach?
I was just asking a question to make sure the algorithm is supposed to be better than O(n) even in the absolute worst case.
M is an input to the program, right? And are there any other constraints on Array?
what do you mean without repetition? do you mean that the numbers are distinct?
yes.Please tell the approach
if M is small, suppose we want to find b: so we start from the first element, if the element is b, we are done. else we will jump |(a[cur]-b)/M|+1 steps. this is because we know anything in between would not be able to be equals to b. Repeat until we find b.
The time complexity of the algorithm is proportional to the number of jumps. And we know that at worst case we can only have 2*M jumps of length 1, 2*M jumps of length 2 and so on till 2*M jumps of length x.
So we have 2M(1+2+...+x) = N-1 as the sum of the jumps can be as most N-1. So (x+1)x = (N-1)/M, and x is about sqrt((N-1)/M), so the number of jumps is 2M*sqrt((N-1)/M) = 2*sqrt((N-1)M)
So the time complexity is O(sqrt(N*M)), it is better than O(N) if M is < N, and if M is greater than N, the complexity is O(N) as there is still at most N jump.
Maybe i misunderstood the problem, but how can we do it faster than reading array? If it is problem with Q queries, why can't we just memorize position of each value, i.e. will make map, where m[i] — position of number i and answer in O(logN) for each query. If it is correct it can be done in O((N + Q)logN) or in O(NlogN + Q). But if this task is interactive i don't know what to do.
usually in this kind of situation, the array will be given, so can you consider the time complexity without reading the array.