Loading…
Data Structures & Algorithms · short notes, key points and practice questions.
Original coding-round problems asked as code-reasoning MCQs, in the style of product-company online assessments and the coding sections of TCS NQT, Infosys and Accenture: read a short problem, then predict a function's output, pick the approach that fits n ≤ 10⁵, find the buggy line, handle an edge case or choose the right data structure. Covers arrays, strings, hashing, linked lists, trees, graphs, heaps, binary search, backtracking, DP, greedy, bit tricks and modular arithmetic.
def pair(w, target):
seen = {}
for i, x in enumerate(w):
if target - x in seen:
return (seen[target - x], i)
seen[x] = i
return None
print(pair([5, 1, 8, 3, 6], 9))What does this function print?Answer: D. (1, 2)
def rotate(a, k):
n = len(a)
k %= n
def rev(i, j):
while i < j:
a[i], a[j] = a[j], a[i]
i += 1; j -= 1
rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
return a
print(rotate([10, 20, 30, 40, 50, 60], 8))What is printed?Answer: D. [50, 60, 10, 20, 30, 40]
def count_k(a, k):
seen = {0: 1}
p = ans = 0
for x in a:
p += x
ans += seen.get(p - k, 0)
seen[p] = seen.get(p, 0) + 1
return ans
print(count_k([1, -1, 1, -1, 1], 1))What is printed?Answer: D. 6
from collections import Counter
def min_window(s, t):
need, missing = Counter(t), len(t)
l = 0; best = (0, float('inf'))
for r, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0:
if r - l < best[1] - best[0]:
best = (l, r)
need[s[l]] += 1
if need[s[l]] > 0:
missing += 1
l += 1
return "" if best[1] == float('inf') else s[best[0]:best[1] + 1]
print(min_window("XAYBZAXB", "ABX"))What is printed?Answer: C. AXB
Answer: C. One pass with a hash set of values seen so far – O(n) average time, O(n) space