ProgrammingModerate
Which loop is correct and fast enough to find the largest element of an array of 10^7 ints, reading each value once?
- A. Sorting the array first and then scanning, about 2 x 10^8 steps
- B. Comparing each element with every other element, about 10^14 steps
- C. Building a binary tree from every element, about 10^8 nodes
- D. A single pass keeping the running maximum, O(n)
Correct answer: D. A single pass keeping the running maximum, O(n)
A single linear pass is the fastest. Sorting is O(n log n), and pairwise comparison is quadratic.
More C Programming questions
- 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…
- 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?