Data Structures & AlgorithmsVery hardAmazon · Microsoft OA
What is the time complexity of this loop?
What is the time complexity of this loop?
i = n
while i > 0:
for j in range(i):
work() # O(1)
i //= 2- A. Θ(n log n)
- B. Θ(log² n)
- C. Θ(n²)
- D. Θ(n)
Correct answer: D. Θ(n)
The inner loop runs n + n/2 + n/4 + … < 2n times in total, a geometric series, so the whole thing is Θ(n). Multiplying 'log n outer iterations × up to n inner' gives only an upper bound of n log n, which is not tight.
More Coding Interview Problems questions
- Recursive quicksort can need O(n) stack depth on adversarial input. Which change GUARANTEES O(log n) extra stack space even in the worst…
- Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties)…
- Problem: Count subarrays with EXACTLY k distinct values using exactly(k) = atMost(k) − atMost(k − 1). python def atmost(a, k): cnt, l, res…
- Find the bug: the code below should return the length of the longest substring without repeating characters. python def longest(s): last…
- Problem: Count the UNIQUE triplets (as value sets) that sum to zero, using sort + two pointers with duplicate skipping. python def…
- Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts). python def count(a…