Prepare Interview

Mock Exams

Make Homepage

## Experienced / Expert level questions & answers

### Ques 1. Implement a function to find the intersection of two lists.

def intersection(list1, list2):

return list(set(list1) & set(list2))

Example:

intersection([1, 2, 3], [2, 3, 4])  # Output: [2, 3]

### Ques 2. Write a Python program to perform matrix multiplication.

import numpy as np

matrix1 = np.array([[1, 2], [3, 4]])

matrix2 = np.array([[5, 6], [7, 8]])

result = np.dot(matrix1, matrix2)

Example:

print(result)
# Output: [[19, 22], [43, 50]]

### Ques 3. Create a generator function to generate Fibonacci numbers.

def fibonacci_generator():

a, b = 0, 1

while True:

yield a

a, b = b, a + b

Example:

fib_gen = fibonacci_generator()
print(next(fib_gen))  # Output: 0

### Ques 4. Implement a depth-first search (DFS) algorithm for a graph.

def dfs(graph, node, visited):

if node not in visited:

print(node)

for neighbor in graph[node]:

dfs(graph, neighbor, visited)

Example:

graph = {1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [], 6: []}
visited_set = set()
dfs(graph, 1, visited_set)

### Ques 5. Implement a function to check if a binary tree is balanced.

class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

def is_balanced(root):
if root is None:
return True
left_height = height(root.left)
right_height = height(root.right)
return abs(left_height - right_height) <= 1 and is_balanced(root.left) and is_balanced(root.right)

def height(node):
if node is None:
return 0
return max(height(node.left), height(node.right)) + 1

Example:

# Example usage: Check if 'root' is a balanced binary tree
is_balanced(root)

### Ques 6. Write a Python program to implement a simple LRU (Least Recently Used) cache.

from collections import OrderedDict

class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity

def get(self, key):
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1

def put(self, key, value):
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
self.cache.move_to_end(key)

Example:

# Example usage:
lru_cache = LRUCache(3)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
lru_cache.put(3, 3)
print(lru_cache.get(2))  # Output: 2