Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024?
Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024?
def cnt(n):
c = 0
for i in range(n):
j = 1
while j < n:
j *= 2; c += 1
return c
print(cnt(1024), cnt(1000))What is printed?- A. 1048576 1000000
- B. 10240 9000
- C. 2047 1999
- D. 10240 10000
Correct answer: D. 10240 10000
The inner loop doubles j from 1 until it reaches n: ⌈log₂ n⌉ steps (10 for both 1024 and 1000), independent of i. Total n·⌈log₂ n⌉ → O(n log n): 1024 × 10 and 1000 × 10. Treating it as O(n²) (the first wrong option) ignores the doubling.
More Coding Interview Problems questions
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…
- Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair…
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…