Skip to content
C

Python Interview Questions

Algorithms & Data Structures Interview Questions

Time/space complexity, common data-structure patterns (Counter, deque, stack, queue, heap), sorting, and caching.

Question 1: What is time complexity?

Ans

Time complexity describes how an algorithm's running work grows with input size. Common classes include O(1), O(log n), O(n), O(n log n), and O(n²).

Example

python
# One pass through n items is typically O(n) for x in values: print(x)

Important Point

State complexity for the actual algorithm, not simply for the Python syntax.

Question 2: What is space complexity?

Ans

Space complexity describes how extra memory usage grows with input size, excluding or including output according to the stated convention.

Example

python
seen = set(values) # extra memory can grow with n

Important Point

Always clarify whether you are discussing auxiliary space or total space.

Question 3: How do you find duplicates in a list?

Ans

Use a set to track values already seen and collect values that appear again.

Example

python
values = [1, 2, 3, 2, 4, 1] seen, duplicates = set(), set() for x in values: if x in seen: duplicates.add(x) else: seen.add(x) print(duplicates)

Important Point

This is O(n) average time and O(n) extra space.

Question 4: How do you count word frequency?

Ans

Split the text into words and count them with collections.Counter or a dictionary.

Example

python
from collections import Counter text = "python is easy python is popular" print(Counter(text.split()))

Important Point

Normalize case and punctuation first when the business requirement considers them equivalent.

Question 5: What is Counter?

Ans

collections.Counter is a dictionary-like class specialized for counting hashable values.

Example

python
from collections import Counter print(Counter("banana"))

Important Point

Counter can return zero for missing keys, but it is still important to understand how zero/negative counts behave in its specialized operations.

Question 6: What is defaultdict?

Ans

collections.defaultdict supplies a default value through a factory when a missing key is accessed.

Example

python
from collections import defaultdict groups = defaultdict(list) groups["Java"].append("Amit") print(groups)

Important Point

Accessing a missing key creates it, so use `get()` when you do not want that side effect.

Question 7: What is deque?

Ans

collections.deque is a double-ended queue optimized for appending and removing from both ends.

Example

python
from collections import deque q = deque([1, 2]) q.appendleft(0) q.append(3) print(q)

Important Point

For frequent front removals, deque is preferable to list because list.pop(0) shifts elements.

Question 8: How do you implement a stack in Python?

Ans

A list can implement a stack efficiently using append() for push and pop() for removing the top element.

Example

python
stack = [] stack.append(10) stack.append(20) print(stack.pop())

Important Point

Use deque when you need efficient operations at both ends.

Question 9: How do you implement a queue?

Ans

Use collections.deque so enqueue and dequeue from opposite ends are efficient.

Example

python
from collections import deque q = deque() q.append("A") q.append("B") print(q.popleft())

Important Point

Avoid list.pop(0) for large queues because it is O(n).

Question 10: How do you reverse a list?

Ans

Use slicing, reversed(), or an in-place two-pointer approach depending on whether a new list or mutation is required.

Example

python
a = [1, 2, 3] print(a[::-1]) a.reverse() print(a)

Important Point

`reverse()` mutates the list and returns None; `reversed()` returns an iterator.

Question 11: How do you check palindrome?

Ans

Compare the sequence with its reverse or use two pointers from the ends.

Example

python
def palindrome(s): return s == s[::-1] print(palindrome("level"))

Important Point

For case-insensitive or normalized text, normalize before comparing.

Question 12: How do you find the largest element?

Ans

Use the built-in max() or scan once while maintaining the current maximum.

Example

python
values = [10, 4, 25, 7] print(max(values))

Important Point

An empty iterable raises ValueError unless a default is supplied to max().

Question 13: How do you sort a list of dictionaries?

Ans

Use sorted() or list.sort() with a key function that extracts the desired field.

Example

python
students = [{"name":"A", "marks":80}, {"name":"B", "marks":95}] print(sorted(students, key=lambda x: x["marks"], reverse=True))

Important Point

Python's sort is stable, so equal-key elements retain their relative order.

Question 14: What is stable sorting?

Ans

A stable sort preserves the original relative order of elements with equal sort keys.

Example

python
items = [("A", 2), ("B", 1), ("C", 2)] print(sorted(items, key=lambda x: x[1]))

Important Point

Python's built-in sort is stable and uses Timsort.

Question 15: What is Timsort?

Ans

Timsort is the hybrid stable sorting algorithm used by Python's built-in list sorting and sorted(). It performs well on partially ordered real-world data.

Example

python
values = [5, 1, 4, 2, 3] values.sort()

Important Point

The implementation details are optimized internally; interview answers should focus on stability and typical O(n log n) worst-case behavior.

Question 16: What is bisect?

Ans

The bisect module provides binary-search-based insertion and search helpers for maintaining sorted lists.

Example

python
import bisect values = [10, 20, 40] bisect.insort(values, 30) print(values)

Important Point

Searching is O(log n), but inserting into a Python list is O(n) because elements may need to shift.

Question 17: What is heapq?

Ans

heapq provides a min-heap implementation over a Python list and is useful for priority queues and top-k problems.

Example

python
import heapq h = [5, 1, 3] heapq.heapify(h) print(heapq.heappop(h))

Important Point

The heap list is not fully sorted; only the heap property is guaranteed.

Question 18: What is itertools?

Ans

itertools contains efficient iterator-building tools such as chain, combinations, permutations, groupby, and product.

Example

python
from itertools import combinations print(list(combinations([1,2,3], 2)))

Important Point

Many itertools functions are lazy, which can save memory for large pipelines.

Question 19: What is functools?

Ans

functools provides higher-order function utilities such as reduce, partial, wraps, cache, and singledispatch.

Example

python
from functools import partial double = partial(pow, exp=2) print(double(3))

Important Point

Understand the resulting callable signature/behavior when using partial or decorators.

Question 20: What is lru_cache?

Ans

functools.lru_cache memoizes function results for hashable arguments, avoiding repeated computation.

Example

python
from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) print(fib(30))

Important Point

Caching trades memory for speed and only works when the function's result is appropriate to cache.

Question 21: What is caching?

Ans

Caching stores previously computed or fetched results so future requests can be served faster or with less work.

Example

python
cache = {} def square(n): if n not in cache: cache[n] = n * n return cache[n]

Important Point

A cache needs an invalidation or eviction strategy when data can become stale or memory is limited.

Question 22: Why is list indexing O(1)?

Ans

Python lists are dynamic arrays in CPython, so an index can be translated to an offset in the underlying array for direct access.

Example

python
values = [10, 20, 30] print(values[2])

Important Point

This describes the common CPython list implementation; inserting at the front is still O(n).

Question 23: Why is dictionary lookup usually O(1)?

Ans

Python dictionaries use hash-table techniques to locate a key by its hash, giving average-case constant-time lookup.

Example

python
data = {"id": 101} print(data["id"])

Important Point

Worst-case behavior can differ, and hashability/equality rules determine whether a key can be used.

Question 24: Why must dictionary keys be hashable?

Ans

A dictionary uses a key's hash to choose a lookup location and equality to resolve matching keys. A mutable object whose hash changes would break those assumptions.

Example

python
key = (1, 2) data = {key: "point"} print(data[key])

Important Point

Hashability requires a stable hash consistent with equality during the key's lifetime.

Question 25: What happens when a key is assigned twice?

Ans

Assigning an existing dictionary key replaces its associated value while keeping that key's identity in the mapping.

Example

python
d = {"role": "user"} d["role"] = "admin" print(d)

Important Point

A dictionary cannot contain two separate entries with equal keys.

Question 26: What is insertion order in dictionaries?

Ans

Python dictionaries preserve insertion order as a language guarantee in modern Python versions. Updating an existing key does not move it to a new position by default.

Example

python
d = {"a": 1, "b": 2} d["a"] = 9 print(list(d))

Important Point

Do not confuse insertion-order preservation with sorting.

Question 27: Why are sets unordered?

Ans

Sets are designed around hashing and uniqueness rather than positional access. Their iteration order should not be treated as a meaningful sorted or insertion order.

Example

python
s = {3, 1, 2} print(2 in s)

Important Point

Do not rely on a particular printed set order.

Question 28: What is memoization?

Ans

Memoization caches function results keyed by inputs so repeated calls can avoid repeated computation.

Example

python
from functools import cache @cache def square(n): return n*n print(square(10))

Important Point

Memoization is appropriate for deterministic computations with reusable results and manageable cache size.

Question 29: What is functools.partial?

Ans

partial() creates a new callable with some arguments of another callable pre-filled.

Example

python
from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) print(square(5))

Important Point

Partial application can simplify callbacks and configuration-heavy APIs.

Continue Your Preparation