Data Structures & AlgorithmsHardAmazon · Microsoft OA
What is the time complexity of this loop?
What is the time complexity of this loop?
for i in range(1, n + 1):
j = i
while j <= n:
work() # O(1)
j += i- A. Θ(n²)
- B. Θ(n)
- C. Θ(n log n)
- D. Θ(n log log n)
Correct answer: C. Θ(n log n)
For each i the inner loop runs ⌊n/i⌋ times, and n/1 + n/2 + … + n/n = n·H(n) ≈ n ln n. This harmonic-sum pattern is how a sieve of divisors runs in O(n log n); the sieve of Eratosthenes, which loops only over primes, is O(n log log n).
More Coding Interview Problems questions
- Problem: Maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best = a[0] for x in…
- Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points…
- Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost. python def…
- Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed. python def robline(a): take…
- Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first…
- Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA −…