Data Structures & AlgorithmsHardGATE CS · TCS NQT · Product Company SDE
What does this code compute, and what is its time complexity for an array of n elements?
What does this code compute, and what is its time complexity for an array of n elements?
int best = a[0]; for (int i = 1; i < n; i++) if (a[i] > best) best = a[i];
- A. The minimum, in O(log n)
- B. The maximum, in O(n)
- C. The maximum, in O(n^2)
- D. The sum, in O(n)
Correct answer: B. The maximum, in O(n)
A single pass keeps the largest value seen so far, which finds the maximum in one linear scan, O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Quicksort uses the Lomuto partition with the last element as pivot on [99, 24, 44, 86, 76, 60, 84, 3]. After one partition call, at which…
- What is the time complexity of this code, as a function of n? c for (int i = 0; i < n; i++) for (int j = i; j < n; j++) sum += a[i] a[j];
- A sorted array is [1, 9, 9, 10, 13, 14, 18, 23, 23, 25]. Using the standard two-pointer in-place duplicate-removal technique (a slow…
- What is the time complexity of reading the element arr[i] from an array of n elements, given i?
- Which data structure works on the Last In, First Out (LIFO) principle?
- What is the worst-case time complexity of binary search on a sorted array of n elements?