Data Structures & AlgorithmsVery hardGATE CS · TCS NQT · Product Company SDE
What is the time complexity of this code, as a function of n?
What is the time complexity of this code, as a function of n?
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
sum += a[i] * a[j];- A. O(n)
- B. O(n log n)
- C. O(n^2)
- D. O(n^3)
Correct answer: C. O(n^2)
The inner loop runs n-i times; summed over i from 0 to n-1 this is n + (n-1) + ... + 1 = O(n^2), even though the inner loop shrinks.
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
- 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?
- Which of these sorting algorithms is stable in its standard implementation?
- What is the time complexity of inserting a new node at the head of a singly linked list of n nodes?