+ 1

space complexity of this algorithm?

int searchNumOccurrence(vector<int> &V, int k, int start, int end) { if (start > end) return 0; int mid = (start + end) / 2; if (V[mid] < k) return searchNumOccurrence(V, k, mid + 1, end); if (V[mid] > k) return searchNumOccurrence(V, k, start, mid - 1); return searchNumOccurrence(V, k, start, mid - 1) + 1 + searchNumOccurrence(V, k, mid + 1, end); }

22nd Sep 2018, 10:46 AM
Bahubali
Bahubali - avatar
12 ответов
+ 1
Use in last case binary search to find first previous and first next for k element. Example: This right part of your vector after you find k: kkkkkkkkkkkkyyyyyyyyyyyyyyyyyyyy Didn't need search all k-element with O(n) You can use binary search O(logn) to find first NoK-element after last k-element. kkkkkkkkkkkk(y)yyyyyyyyyyyyyyyyyyy
22nd Sep 2018, 6:05 PM
Lair
0
This algorithm will only work on an ordered vector. Use "else if" for readability. O(logn) if no element in vector. O(n) if all element =k. In last case you can use linear search previous and next element !=k instead of using recursion.
22nd Sep 2018, 1:54 PM
Lair
0
yes element will be sorted.how is o(n) can u please elaborate?
22nd Sep 2018, 1:58 PM
Bahubali
Bahubali - avatar
0
You should use best algoritm to find element !=k on the sides of the element k. (This last case) Linear search isn't best.
22nd Sep 2018, 2:13 PM
Lair
0
aaaabbbccckkkkkkkkkyyyyzzz m - amount of elements =k In this example m=9 Your algoritm O(logn+m)
22nd Sep 2018, 2:16 PM
Lair
0
Best algoritm have O(logn + logm)
22nd Sep 2018, 2:18 PM
Lair
0
are u talking about space or time complexity?
22nd Sep 2018, 2:20 PM
Bahubali
Bahubali - avatar
0
Time
22nd Sep 2018, 2:21 PM
Lair
0
ok what is space complexity of this algorithm?
22nd Sep 2018, 2:23 PM
Bahubali
Bahubali - avatar
0
Only recursion stack Perhaps O(logn *m) logn*m < n
22nd Sep 2018, 2:30 PM
Lair
0
i think it will be o(n) because in the worst case all element will be k and last return statement will be executed always
22nd Sep 2018, 2:44 PM
Bahubali
Bahubali - avatar
0
yes thank u so much for ur time
22nd Sep 2018, 6:08 PM
Bahubali
Bahubali - avatar