Data Structures & AlgorithmsHardProduct-company MCQ pattern
What is the time complexity of this code fragment?
What is the time complexity of this code fragment?
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j += i)
work(); // O(1)- A. O(n √n)
- B. O(n log n)
- C. O(n)
- D. O(n²)
Correct answer: B. O(n log n)
For each i the inner loop runs about n/i times, so the total is n(1 + 1/2 + … + 1/n) = n·Hₙ ≈ n ln n = O(n log n). The step j += i is what stops it being 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
- What value of count does this code print for n = 16? c int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count++…
- What does this code print? c int c = 0, n = 10; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n…
- Keys 12, 22, 32 are inserted into a size-10 table with h(k) = k mod 10 and linear probing. Then 22 is deleted by simply setting its slot…
- Keys 18, 41, 22, 44, 59, 32, 31, 96 are inserted in that order into a table of size 13 by double hashing: h₁(k) = k mod 13, h₂(k) = 7 − (k…
- 1, 2, 3, 4 are pushed onto a stack in this order, with pops allowed at any time. How many of the 24 permutations can be produced as the…
- A queue uses two stacks: enqueue pushes onto IN; dequeue pops from OUT, first moving ALL of IN into OUT only if OUT is empty. For enq 1…