ProgrammingHard
A program must answer 10^6 queries 'is x present in the set S?' where S has 10^6 values fixed in advance. Which preprocessing and query cost is correct and fast enough?
- A. Sort S once in O(n log n), then each query is a binary search in O(log n), about 2 x 10^7 steps total
- B. Scan S for each query, about 10^12 steps
- C. Sort S before each query, about 10^13 steps
- D. Compare x with all pairs in S, about 10^12 steps
Correct answer: A. Sort S once in O(n log n), then each query is a binary search in O(log n), about 2 x 10^7 steps total
Preprocessing is O(n log n) once and queries cost O(log n), so the total stays near 2 x 10^7. Scanning S each time is quadratic.
More C Programming questions
- How many times does a body run in for (int i = 2; i < 100; i = i)?
- Which change makes the loop for (int i = 0; i < strlen(s); i++) run in linear time?
- A 2D grid of 2000 x 2000 cells is searched by a BFS that visits each cell once. About how many cell visits happen?
- A program finds the number of pairs (i, j) with i < j among n = 10^5 elements by a nested loop. How many pair checks happen?
- For n = 10^6, which C code computes the sum of the first n integers in O(1) without overflow in 64-bit long long?
- Which condition makes a loop with an int index i and a sizet bound n safe from an infinite loop when n is 0?