Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
B.Tech S3 (R) (FT/WP) Examination November 2025 (2024 Scheme)QP 06PCCST303112503Part A · Q13 marksCO1Module 1asked in 2 papers

Question 1

Compute the time complexity of the following code fragment. for(i=0;i<n;i++) for(j=n;j>0;j=j/2) printf("DATA STRUCTURE");

Topics: Performance analysis: time and space complexity

Solution

Assumptions:
  • n ≥ 1 and integer division (j = j/2 truncates).

Outer loop: i = 0 … n − 1 → n iterations. Inner loop: j takes values n, ⌊n/2⌋, ⌊n/4⌋, …, 1 and stops at 0 → ⌊log₂ n⌋ + 1 iterations, independent of i.

T(n) = n · (⌊log₂ n⌋ + 1) ⇒ T(n) = Θ(n log n)

Check with n = 8: j = 8, 4, 2, 1 → 4 = log₂8 + 1 iterations; total 8 × 4 = 32 prints.

How to write it in the exam

The printf executes n(⌊log₂ n⌋ + 1) times, so the time complexity is O(n log n).

How this answer was verified
  • tests/complexity.test.ts (iteration count checked for n = 1 … 2000)

Similar questions