ProgrammingHard
To answer 'how many times does x appear in a sorted array' in O(log n), which pair of searches is correct?
- A. A linear scan from both ends, which is O(n)
- B. One binary search that stops at the first x, then counts by scanning
- C. Sorting again before each query
- D. lower_bound(x) and upper_bound(x), and the answer is their difference
Correct answer: D. lower_bound(x) and upper_bound(x), and the answer is their difference
The difference of the two bounds gives the count in O(log n) time for any number of duplicates.
More C Programming questions
- A bit array for flags of 10^9 items is held as one byte per item. What is the memory use, and is it fast enough in typical limits?
- struct P { char a; int b; char c; }; printf("%zu", sizeof(struct P)); What is printed with 4-byte int and natural alignment?
- struct P { char a; int b; }; printf("%zu", offsetof(struct P, b)); What is printed with 4-byte int and natural alignment (stddef.h…
- struct R { int v; struct R next; }; struct R c = {3, NULL}, b = {2, &c}, a = {1, &b}; printf("%d", a.next->next->v); What is printed?
- struct Pt { int x, y; }; struct Pt pts[3] = {{1, 2}, {3, 4}, {5, 6}}; struct Pt p = pts + 1; printf("%d %d", p->x, (p - pts)); What is…
- struct Item { int id; int qty; }; struct Item a[2] = {{1, 5}, {2, 7}}; struct Item b = a[1]; b.qty = 0; printf("%d %d", a[1].qty, b.qty)…