Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: A function does `for i in range(n): for j in range(i, n, i + 1): work()`. What is its time complexity?
- A. O(n²)
- B. O(n)
- C. O(n √n)
- D. O(n log n) – the inner loop runs about n/(i + 1) times, and Σ n/k is a harmonic sum
Correct answer: D. O(n log n) – the inner loop runs about n/(i + 1) times, and Σ n/k is a harmonic sum
For each i the inner loop steps by i + 1 from i to n: roughly n/(i + 1) iterations. Summing n/1 + n/2 + … + n/n = n·Hₙ ≈ n ln n. This is the same pattern as the sieve's inner loop. It is not quadratic because the step grows.
More Coding Interview Problems questions
- Problem: A recursive function on n does O(1) work and makes two calls on n/2. What is T(n)?
- Problem: Inside a loop of n iterations, the code calls Python's list.pop(0) and Java's String +=. What is the real complexity of the loop?
- Problem: For n = 10⁶ distinct integers up to 10⁹, find the smallest positive integer missing from the array in O(n) time and O(1) extra…
- Problem: Find the smallest missing positive integer using cyclic placement. python def firstmissing(a): n = len(a) for i in range(n)…
- Problem: Binary search for x in a sorted int array (C++): cpp int lo = 0, hi = n - 1; while (lo <= hi) { int mid = (lo + hi) / 2; // line…
- Problem: Kadane's algorithm (Java): java int best = 0, cur = 0; // line 1 for (int x : a) { cur = Math.max(x, cur + x); // line 3 best =…