State the approach and complexity out loud before coding.
Q85. Two Sum: return indices of two numbers adding to a target.
One pass with a hash map. Time O(n), space O(n).
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = iQ86. Are two strings anagrams?
Time O(n).
from collections import Counter
def is_anagram(a, b):
return Counter(a) == Counter(b)Q87. Group anagrams together.
Use the sorted word as the key. Time O(n k log k).
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())Q88. Valid parentheses.
Use a stack. Time O(n).
def valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for c in s:
if c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
else:
stack.append(c)
return not stackQ89. First non-repeating character.
from collections import Counter
def first_unique(s):
counts = Counter(s)
for i, c in enumerate(s):
if counts[c] == 1:
return i
return -1Q90. Longest substring without repeating characters.
Sliding window with last-seen index. Time O(n).
def longest_unique(s):
last, start, best = {}, 0, 0
for i, c in enumerate(s):
if c in last and last[c] >= start:
start = last[c] + 1
last[c] = i
best = max(best, i - start + 1)
return bestQ91. Merge overlapping intervals.
Sort by start, then extend or append. Time O(n log n).
def merge(intervals):
out = []
for s, e in sorted(intervals):
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outQ92. Implement an LRU cache.
OrderedDict keeps order; get and put are O(1). Very common in AI-engineer rounds (caching LLM responses).
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict least recently usedQ93. Flatten an arbitrarily nested list.
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]Q94. Top-k most frequent words.
most_common uses a heap internally, roughly O(n log k).
from collections import Counter
import re
def top_words(text, k=3):
words = re.findall(r"[a-z']+", text.lower())
return Counter(words).most_common(k)Q95. Rapid-fire theory questions to prepare
listvsarraymodule vs NumPy array?listholds any objects;array.arrayholds one primitive type compactly; NumPy adds vectorized math and n-dimensional shapes.What is
__slots__? It fixes an object's attributes up front, removing the per-instance__dict__and cutting memory.How does Python manage memory? Reference counting frees objects at zero references; a cyclic garbage collector handles reference cycles.
What is monkey patching? Replacing attributes or functions at runtime. Acceptable mainly in tests (
unittest.mock.patch), risky elsewhere.dequevslistfor queues?collections.dequepops from both ends in O(1);list.pop(0)is O(n).yield fromandsend()?yield fromdelegates to a sub-generator;send()pushes a value into a paused generator (the basis of old-style coroutines).What do
__call__,__getitem__,__iter__,__enter__do? They make objects callable like functions, indexable (obj[i]), iterable, and usable inwithblocks.Why is
x in listslower thanx in set? A list scans every element, O(n); a set hashes the value and jumps to it, O(1) on average.What is a race condition? Two threads read and modify shared state in an unpredictable order. Use a
threading.Lock(or avoid shared mutable state) to prevent it.