0% found this document useful (0 votes)
6 views50 pages

Python Quetions

The document is a collection of Python interview questions and answers, focusing on array manipulation and algorithms. It includes functions for finding intersections, differences, duplicates, flattening nested lists, and calculating maximum products and sums. Each solution is accompanied by explanations and examples to illustrate the concepts.

Uploaded by

MIMIAU
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views50 pages

Python Quetions

The document is a collection of Python interview questions and answers, focusing on array manipulation and algorithms. It includes functions for finding intersections, differences, duplicates, flattening nested lists, and calculating maximum products and sums. Each solution is accompanied by explanations and examples to illustrate the concepts.

Uploaded by

MIMIAU
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Interview Questions

Cookbook
Given two arrays, write a python function to return the
intersection of the two? For example, X = [1,5,9,0] and
Y = [3,0,2,9] it should return [9,0]
set(X).intersect (set(Y))

What it does:
Returns a set of elements common to both X and Y

Does not preserve order


Removes duplicates

X = [1, 5, 9, 0]
Y = [3, 0, 2, 9]

result = set(X).intersection(set(Y))
print(result) # Output: {0, 9} — order is not guaranteed

If you want it as a list:


python
CopyEdit
list(set(X) & set(Y)) # OR list(set(X).intersection(set(Y)))

Interview Caution:
If the interviewer cares about order preservation or duplicates, this solution is
not valid. Otherwise, it's a great one-liner.

Python Interview Questions Cookbook 1


Python Function (Using List Comprehension)
python
CopyEdit
def intersection(X, Y):
return [item for item in X if item in Y]

Given two lists X and Y , return a list of elements that


are in X but not in Y , preserving the order in X .
Example:

python

X = [1, 5, 9, 0]
Y = [3, 0, 2, 9]

Expected Output:

python
CopyEdit
[1, 5]

Answer:
python
CopyEdit
def difference(X, Y):
set_Y = set(Y)
return [item for item in X if item not in set_Y]

Python Interview Questions Cookbook 2


Explanation in Steps:
1. Convert list Y to a set to allow for faster lookup.
Set lookup is O(1), so this improves efficiency compared to using if item

not in Y .

2. Use a list comprehension to iterate through elements of X .


3. For each item in X , check if it's not in Y .
4. If the condition is true, include it in the result list.
5. Return the final list that only contains elements unique to X .

Given a list of integers, return the first duplicate


element you encounter. If there are no duplicates,
return None .
Example:

python
CopyEdit
X = [2, 5, 1, 2, 3, 5]

Expected Output:

python
CopyEdit
2

Answer:
python
CopyEdit
def first_duplicate(X):

Python Interview Questions Cookbook 3


seen = set()
for item in X:
if item in seen:
return item
[Link](item)
return None

Explanation in Steps:
1. Initialize an empty set seen to keep track of elements we’ve already
encountered.
2. Loop through each element in the list X .
3. For each element:
Check if it already exists in seen .
If it does, that’s the first duplicate, so return it immediately.
If not, add it to seen and continue.
4. If the loop finishes without finding a duplicate, return None .

Given a nested list of integers, write a function that


flattens it into a single list of integers.
You don’t know how deep the nesting goes.
Example:

python
CopyEdit
X = [1, [2, [3, 4], 5], 6]

Expected Output:

Python Interview Questions Cookbook 4


python
CopyEdit
[1, 2, 3, 4, 5, 6]

Answer:
python
CopyEdit
def flatten_list(nested):
result = []
for item in nested:
if isinstance(item, list):
[Link](flatten_list(item))
else:
[Link](item)
return result

Explanation in Steps:
1. Define a recursive function flatten_list that takes one argument: nested .
2. Initialize an empty list called result to store the flattened items.
3. Loop through each item in the given nested list.
4. If item is a list , call the function recursively and extend the result list with the
returned flattened sublist.
5. If item is not a list (i.e., an integer), append it to the result directly.
6. Return the fully flattened list after processing all elements.

Flatten a deeply nested list of integers into a flat list


without using recursion.

Python Interview Questions Cookbook 5


Use an iterative approach (e.g., a stack).
Example:

python
CopyEdit
X = [1, [2, [3, 4], 5], 6]

Expected Output:

python
CopyEdit
[1, 2, 3, 4, 5, 6]

Answer:
python
CopyEdit
def flatten_list_iterative(nested):
result = []
stack = nested[::-1]

while stack:
current = [Link]()
if isinstance(current, list):
[Link](current[::-1])
else:
[Link](current)

return result

Python Interview Questions Cookbook 6


Explanation in Steps:
1. Initialize an empty list result to collect the final flattened values.
2. Use a stack to simulate recursion. We start with the input list nested , but
reversed ( [::-1] ) so we can pop elements in the correct order.
3. Loop until the stack is empty:
Pop an element from the stack.
If it's a list, extend the stack with its elements in reverse order, so we
maintain the original order.
If it's an integer, append it to the result.
4. Return the result once the stack is empty.

Given a list of integers, return a new list with


duplicates removed, but keep the original order of
elements.
Example:

python
CopyEdit
X = [1, 2, 2, 3, 1, 4]

Expected Output:

python
CopyEdit
[1, 2, 3, 4]

Answer:

Python Interview Questions Cookbook 7


python
CopyEdit
def remove_duplicates(X):
seen = set()
result = []
for item in X:
if item not in seen:
[Link](item)
[Link](item)
return result

Explanation in Steps:
1. Create a set named seen to track which elements have already been added.
2. Initialize an empty list result for storing unique elements in order.
3. Iterate over each item in X .
4. If item is not in the seen set:
Add it to seen .
Append it to result .
5. Return the result list — now it contains each number only once, in their first
appearance order.

Return all elements from a list that appear more than


once, preserving their first appearance order.
Example:

python
CopyEdit
X = [4, 5, 2, 4, 3, 5, 4]

Python Interview Questions Cookbook 8


Expected Output:

python
CopyEdit
[4, 5]

Answer:
python
CopyEdit
from collections import Counter

def find_duplicates(X):
count = Counter(X)
result = []
added = set()

for item in X:
if count[item] > 1 and item not in added:
[Link](item)
[Link](item)
return result

Explanation in Steps:
1. Use [Link] to count occurrences of each item.
2. Initialize an empty result list and a set called added to track which duplicates
we’ve already included.
3. Loop through each item in the original list X .
4. If:
The count of the item is greater than 1 (i.e., it’s a duplicate), and

Python Interview Questions Cookbook 9


It hasn’t already been added to the result,
then add it to both result and added .
5. Return the result list.

Given a list of integers, return a list of all elements that


appear more than once.
Example:

python
CopyEdit
X = [1, 2, 3, 1, 3, 6, 5]

Expected Output:

python
CopyEdit
[1, 3]

Answer:
python
CopyEdit
from collections import Counter

def find_duplicates(X):
count = Counter(X)
return [item for item, freq in [Link]() if freq > 1]

Explanation in Steps:

Python Interview Questions Cookbook 10


1. Use Python’s Counter from the collections module to count how many times
each element appears in the list.
2. returns a dictionary-like object where keys are the elements of X ,
Counter(X)

and values are their frequencies.


3. Use a list comprehension to loop through the (item, freq) pairs.
4. Include the item in the result if its frequency freq is greater than 1.
5. Return the final list of duplicates.

Given a list of integers, return a list of all duplicates in


O(n) time.
Try to optimize space usage as much as possible.
Example:

python
CopyEdit
X = [1, 2, 3, 1, 3, 6, 5]

Expected Output:

python
CopyEdit
[1, 3]

Answer (Using Set):


python
CopyEdit
def find_duplicates_optimized(X):
seen = set()
duplicates = set()

Python Interview Questions Cookbook 11


for num in X:
if num in seen:
[Link](num)
else:
[Link](num)

return list(duplicates)

Explanation in Steps:
1. Initialize two sets:
seen : stores elements we've encountered
duplicates : stores elements seen more than once
2. Loop through the list:
If an element is already in seen , it’s a duplicate → add it to duplicates .
Otherwise, add it to seen .
3. Convert duplicates to a list and return it.

Time & Space Complexity:


Time: O(n) — one pass through the list
Space: O(n) — two sets, but still much more efficient than a full Counter map

Given an integer array, return the maximum product of


any three numbers.
Example:

python
CopyEdit

Python Interview Questions Cookbook 12


X = [1, 10, 2, 6, 5, 3]

Expected Output:

python
CopyEdit
300 # 10 * 6 * 5

Now try with negative values:

python
CopyEdit
X = [-10, -10, 1, 3, 2]

Expected Output:

python
CopyEdit
300 # (-10) * (-10) * 3

Answer (Efficient Approach with Sorting):


python
CopyEdit
def max_product_of_three(X):
[Link]()
return max(X[-1] * X[-2] * X[-3], X[0] * X[1] * X[-1])

Explanation in Steps:

Python Interview Questions Cookbook 13


1. Sort the array in ascending order.
2. Consider two possible products:
The product of the three largest numbers: X[-1] * X[-2] * X[-3]

The product of the two smallest (possibly negative) and the largest
number: X[0] * X[1] * X[-1]
This handles cases where multiplying two negatives gives a large positive
result.
3. Return the maximum of these two values.

Given an integer array, return the sum of the largest


contiguous subarray. If all elements are negative,
return 0.
Example:

python
CopyEdit
A = [0, -1, -5, -2, 3, 14]

Expected Output:

python
CopyEdit
17 # from subarray [3, 14]

Answer (Using Kadane’s Algorithm with 0 baseline):


python
CopyEdit
def max_contiguous_sum(A):
max_sum = 0

Python Interview Questions Cookbook 14


current_sum = 0

for num in A:
current_sum += num
if current_sum < 0:
current_sum = 0
max_sum = max(max_sum, current_sum)

return max_sum

Explanation in Steps:
1. Initialize:
max_sum = 0 — this will hold the final answer
current_sum = 0 — this tracks the running sum of the current subarray
2. Loop through each number in the array:
Add the number to current_sum

If current_sum drops below 0, reset it to 0 (start a new subarray)


Update max_sum if current_sum is greater than max_sum

3. After the loop, max_sum contains the highest contiguous subarray sum found.
4. This approach also returns 0 when all numbers are negative, which matches
your requirement.

Given an integer array, return the sum of the largest


contiguous subarray of non-negative numbers.
If there's a tie in sum, return the longest subarray. If still tied, return the first one.
Example:

python
CopyEdit

Python Interview Questions Cookbook 15


A = [1, 2, 5, -7, 2, 3]

Expected Output:

python
CopyEdit
8 # from subarray [1, 2, 5]

Answer:
python
CopyEdit
def max_non_negative_subarray_sum(A):
max_sum = 0
max_len = 0
current_sum = 0
current_len = 0

for num in A:
if num >= 0:
current_sum += num
current_len += 1
else:
if (current_sum > max_sum or
(current_sum == max_sum and current_len > max_
len)):
max_sum = current_sum
max_len = current_len
current_sum = 0
current_len = 0

# Final check in case best subarray is at the end


if (current_sum > max_sum or

Python Interview Questions Cookbook 16


(current_sum == max_sum and current_len > max_len)):
max_sum = current_sum

return max_sum

Explanation in Steps:
1. Initialize variables:
max_sum , max_len to track the best subarray so far
current_sum , current_len to track the current non-negative run
2. Loop through each number:
If non-negative, add to the current run
If negative, evaluate whether the just-ended run is the new best
3. After the loop, check one last time if the final segment was the best (in case
the array ended on a non-negative sequence).
4. Return the max_sum found.

Given an integer array, return the actual contiguous


subarray of non-negative numbers that has the
maximum sum.
Apply the same tie-breaking rules:
If multiple subarrays have the same sum, return the longest one.
If still tied, return the one that appears first.
Example:

python
CopyEdit
A = [1, 2, 5, -7, 2, 3]

Python Interview Questions Cookbook 17


Expected Output:

python
CopyEdit
[1, 2, 5]

Answer:
python
CopyEdit
def max_non_negative_subarray(A):
max_sum = -1
max_len = 0
max_start = -1

current_sum = 0
current_start = 0
current_len = 0

for i, num in enumerate(A):


if num >= 0:
if current_len == 0:
current_start = i
current_sum += num
current_len += 1
else:
if (current_sum > max_sum or
(current_sum == max_sum and current_len > max
_len)):
max_sum = current_sum
max_len = current_len
max_start = current_start
current_sum = 0
current_len = 0

Python Interview Questions Cookbook 18


# Final check in case best subarray is at the end
if (current_sum > max_sum or
(current_sum == max_sum and current_len > max_len)):
max_sum = current_sum
max_len = current_len
max_start = current_start

if max_start == -1:
return []
return A[max_start:max_start + max_len]

Explanation in Steps:
1. Track both the current subarray ( current_sum , current_len , current_start ) and
the maximum subarray so far ( max_sum , max_len , max_start ).
2. Loop through the array:
If number is non-negative, continue the current subarray
If it’s negative:
Compare the current subarray to the best so far (based on sum, then
length)
Reset the current trackers
3. After the loop, check one last time in case the array ended with the best
subarray.
4. Use slicing with max_start and max_len to return the best subarray.

Define tuples and lists in Python What are the major


differences between them?
Definition

Python Interview Questions Cookbook 19


List: A mutable, ordered collection of items that can be changed after
creation.
Declared with square brackets:

python
CopyEdit
my_list = [1, 2, 3]

Tuple: An immutable, ordered collection of items that cannot be changed


after creation.
Declared with parentheses:

python
CopyEdit
my_tuple = (1, 2, 3)

Major Differences
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot change)
Syntax [] square brackets () parentheses
Performance Slightly slower Faster (due to immutability)
Use case For dynamic data For fixed/constant data
Can be a dict key? No Yes
Methods Available Many (append, pop, etc.) Very few (count, index)
Memory Usage More Less

Example:

Python Interview Questions Cookbook 20


python
CopyEdit
# List
fruits = ["apple", "banana"]
[Link]("orange") # Allowed

# Tuple
coordinates = (10, 20)
# coordinates[0] = 30 # Not allowed – will raise a TypeEr
ror

When to Use:
Use lists when you need to modify, add, or remove elements.
Use tuples when your data should not change, like geographical coordinates
or constants.

How do you compute the Euclidean distance between


two numeric series (lists, arrays, etc.) in Python?
Example:

python
CopyEdit
X = [1, 2, 3]
Y = [4, 0, 3]

Expected Output:

python
CopyEdit

Python Interview Questions Cookbook 21


3.605551275463989

Answer (Pure Python):


python
CopyEdit
import math

def euclidean_distance(X, Y):


return [Link](sum((a - b) ** 2 for a, b in zip(X, Y)))

Explanation in Steps:
1. Zip the two lists together: this gives pairs of corresponding elements (a, b) .
2. Subtract each pair, square the result: (a - b)² .
3. Sum all the squared differences.
4. Take the square root of that sum using [Link]() .

Answer (Using NumPy):


python
CopyEdit
import numpy as np

def euclidean_distance_np(X, Y):


return [Link]([Link](X) - [Link](Y))

computes the L2 norm (Euclidean distance) of the difference


[Link]()

between the arrays.

Python Interview Questions Cookbook 22


Given integers n and k , return all combinations of k
numbers from 1 to n .
Example:

python
CopyEdit
n = 3
k = 2

Expected Output:

python
CopyEdit
[[1, 2], [1, 3], [2, 3]]

Answer (Using [Link] ):


python
CopyEdit
from itertools import combinations

def generate_combinations(n, k):


return [list(c) for c in combinations(range(1, n + 1),
k)]

Explanation in Steps:
1. Use range(1, n+1) to generate numbers from 1 to n .
2. Use [Link](iterable, k) to generate all unique combinations
(order doesn’t matter, no repetition).

Python Interview Questions Cookbook 23


3. Convert each combination (which is a tuple) into a list.

Follow-Up (Without Using itertools )


Here’s a recursive approach to solve it manually:

python
CopyEdit
def combine(n, k):
result = []

def backtrack(start, path):


if len(path) == k:
[Link](path[:])
return
for i in range(start, n + 1):
[Link](i)
backtrack(i + 1, path)
[Link]()

backtrack(1, [])
return result

Generate all permutations of k numbers chosen from


1 to n .
This means order does matter.

Example:
python
CopyEdit
n = 3
k = 2

Python Interview Questions Cookbook 24


Expected Output:

python
CopyEdit
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

Answer (Using [Link] ):


python
CopyEdit
from itertools import permutations

def generate_permutations(n, k):


return [list(p) for p in permutations(range(1, n + 1),
k)]

Explanation:
permutations() generates all ordered arrangements of k items from the given
range.
Convert each result from tuple to list to match expected output.

Question 17:
Now add a constraint: only include combinations where all numbers are even.

Example:
python
CopyEdit
n = 6

Python Interview Questions Cookbook 25


k = 2

Expected Output:

python
CopyEdit
[[2, 4], [2, 6], [4, 6]]

Answer (With Even Constraint):


python
CopyEdit
from itertools import combinations

def even_combinations(n, k):


evens = [x for x in range(1, n + 1) if x % 2 == 0]
return [list(c) for c in combinations(evens, k)]

Given a positive integer X , return the factorial of X


using a recursive function. If a negative integer is
given, return -1.
Example:
python
CopyEdit
factorial(5) → 120
factorial(-2) → -1

Answer:

Python Interview Questions Cookbook 26


python
CopyEdit
def factorial(x):
if x < 0:
return -1
if x == 0 or x == 1:
return 1
return x * factorial(x - 1)

Explanation in Steps:
1. Base case 1: If x is less than 0 → return 1 (invalid input).
2. Base case 2: If x is 0 or 1 → return 1 (by definition of factorial).
3. Recursive case:
Multiply x by the result of factorial(x - 1) — this reduces the problem at each
step.

Example Trace (for 4):


matlab
CopyEdit
factorial(4)
→ 4 * factorial(3)
→ 4 * 3 * factorial(2)
→ 4 * 3 * 2 * factorial(1)
→ 4 * 3 * 2 * 1 = 24

Given an m x n matrix of positive integers, return the


length of the longest increasing path.
You can move in 4 directions: up, down, left, and right.

Python Interview Questions Cookbook 27


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Expected Output:
python
Copy
Edit
5 # path: 1 → 2 → 5 → 6 → 9

Answer:
python
CopyEdit
def longest_increasing_path(matrix):
if not matrix or not matrix[0]:
return 0

rows, cols = len(matrix), len(matrix[0])


memo = [[0] * cols for _ in range(rows)]
directions = [(0,1), (1,0), (0,-1), (-1,0)]

def dfs(r, c):


if memo[r][c]:
return memo[r][c]

max_length = 1 # at least the cell itself


for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and matrix[n
r][nc] > matrix[r][c]:
max_length = max(max_length, 1 + dfs(nr, nc))

memo[r][c] = max_length

Python Interview Questions Cookbook 28


return max_length

return max(dfs(r, c) for r in range(rows) for c in range


(cols))

Explanation in Steps:
1. Loop through every cell in the matrix as a potential starting point.
2. Use DFS to explore increasing paths in all four directions.
3. Use a memoization table ( memo ) to store the longest path starting from each
cell — avoids recomputation and makes the solution efficient.
4. From each cell, move to neighbors with a strictly greater value and take the
max path length.
5. Finally, return the maximum length found across all cells.

What is the difference between lists, arrays, and sets


in Python, and when should you use each?
1. Lists ( list )
Definition: Ordered, mutable (changeable), and allows duplicates. Can contain
mixed types (e.g. integers, strings).
Syntax:

python
CopyEdit
my_list = [1, 2, 3, 2]

When to Use:
Use lists when:
You need to preserve order

Python Interview Questions Cookbook 29


You want to allow duplicates
You need dynamic, general-purpose containers

2. Arrays ( [Link] )
Definition: Ordered, mutable, but all elements must be of the same data type.
Requires the array module and is more memory-efficient for large numeric
data.
Syntax:

python
CopyEdit
import array
my_array = [Link]('i', [1, 2, 3])

When to Use:
Use arrays when:
You are dealing with large numeric datasets
You want better performance and memory efficiency than lists
You’re doing lower-level, typed data manipulation
Note: In data science, people often use NumPy arrays ([Link]), which are
far more powerful for numerical operations.

3. Sets ( set )
Definition: Unordered, mutable (but elements must be hashable), and does
not allow duplicates.
Syntax:

python
CopyEdit

Python Interview Questions Cookbook 30


my_set = {1, 2, 3, 2}
print(my_set) # Output: {1, 2, 3}

When to Use:
Use sets when:
You need to eliminate duplicates
You want to perform set operations (union, intersection, difference)
You don’t care about order

Summary Table
Feature List Array Set
Ordered Yes Yes No
Mutable Yes Yes Yes
Duplicates Allowed Allowed Not Allowed
Type Restriction No Yes Elements must be hashable
Use Case General purpose Numeric data Membership checks, deduplication

Given a word (string), count how many consonants it


has.
python
CopyEdit
def count_consonants(word):
vowels = 'aeiou'
count = 0
for char in [Link]():
if [Link]() and char not in vowels:
count += 1
return count

Python Interview Questions Cookbook 31


# Example
print(count_consonants("programming")) # Output: 8

Explanation in Steps:
1. Convert the word to lowercase to handle uppercase letters consistently.
2. Use [Link]() to ensure you only consider letters (ignore spaces,
symbols, etc.).
3. Check if the character is not a vowel.
4. If both conditions are met, increment the count .

How do you count the number of occurrences of a


specific character in a string?
Example:
python
CopyEdit
text = "programming"
char = "m"

Expected Output:

python
CopyEdit
2

Answer 1: Using count() Method

Python Interview Questions Cookbook 32


python
CopyEdit
text = "programming"
char = "m"
occurrences = [Link](char)
print(occurrences) # Output: 2

Answer 2: Manual Loop (Case-Insensitive Example)


python
CopyEdit
def count_char_occurrences(text, target_char):
count = 0
for char in text:
if char == target_char:
count += 1
return count

# Example
print(count_char_occurrences("programming", "m")) # Output:
2

Optional – Case Insensitive


If you want to count both uppercase and lowercase versions (e.g., "A" and "a" ):

python
CopyEdit
text = "Programming"
char = "m"

Python Interview Questions Cookbook 33


occurrences = [Link]().count([Link]())
print(occurrences) # Output: 2

How do you find the middle element(s) in a list?


Cases:
If the list has odd length, return the single middle element.
If the list has even length, return the two middle elements.

Example 1 (Odd Length):


python
CopyEdit
L = [10, 20, 30, 40, 50]
# Middle: 30

Example 2 (Even Length):


python
CopyEdit
L = [1, 2, 3, 4]
# Middle: 2, 3

Answer:
python
CopyEdit
def find_middle(lst):
n = len(lst)
mid = n // 2

Python Interview Questions Cookbook 34


if n == 0:
return None
if n % 2 == 0:
return [lst[mid - 1], lst[mid]]
else:
return lst[mid]

Explanation in Steps:
1. Compute the length of the list and the middle index ( n // 2 ).
2. If the list is empty, return None or an appropriate value.
3. If the length is even, return the two middle elements: lst[mid - 1] and
lst[mid] .

4. If the length is odd, return just the element at index mid .

How do you implement the Singleton pattern in Python


using a metaclass?
✅ Singleton Pattern via Metaclass
python
CopyEdit
class SingletonMeta(type):
_instances = {}

def __call__(cls, *args, **kwargs):


if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **k
wargs)
return cls._instances[cls]

# Class that uses the singleton metaclass

Python Interview Questions Cookbook 35


class SingletonClass(metaclass=SingletonMeta):
def __init__(self, value):
[Link] = value

Explanation in Steps:
1. is a metaclass that overrides the
SingletonMeta __call__ method. This method
is invoked when a class is instantiated.
2. Inside __call__ , we check if an instance of the class already exists in
_instances .
3. If not, we create it with super().__call__() and store it.
4. If it already exists, we return the existing instance — ensuring only one
instance is ever created.

Usage Example:
python
CopyEdit
a = SingletonClass("first")
b = SingletonClass("second")

print([Link]) # Output: first


print([Link]) # Output: first
print(a is b) # Output: True

Even though we tried to instantiate it twice, both a and b are the same object.

Given an unsorted list of integers, return the length of


the longest consecutive elements sequence.
The solution should run in O(n) time.

Python Interview Questions Cookbook 36


Example:
python
CopyEdit
nums = [100, 4, 200, 1, 3, 2]

Expected Output:

python
CopyEdit
4 # The sequence is [1, 2, 3, 4]

Answer (Optimized O(n) using a Set):


python
CopyEdit
def longest_consecutive(nums):
num_set = set(nums)
max_length = 0

for num in num_set:


# Only start counting if it's the beginning of a sequ
ence
if num - 1 not in num_set:
current = num
length = 1

while current + 1 in num_set:


current += 1
length += 1

max_length = max(max_length, length)

Python Interview Questions Cookbook 37


return max_length

Explanation in Steps:
1. Convert the list to a set for O(1) lookups.
2. Iterate through each number in the set.
3. Only start a new sequence if num - 1 is not in the set, meaning it's the
beginning of a sequence.
4. Count how long the consecutive sequence is by checking num + 1 , num + 2 ,
etc.
5. Keep track of the maximum length found.

Time and Space Complexity:


Time: O(n) — each number is processed at most once
Space: O(n) — for the set

Given an unsorted list of integers, return the actual


longest consecutive sequence (as a list), not just its
length.
The sequence must be strictly consecutive (e.g., [1, 2, 3, 4]), and order doesn't
matter in the input.

Example:
python
CopyEdit
nums = [100, 4, 200, 1, 3, 2]

Expected Output:

Python Interview Questions Cookbook 38


python
CopyEdit
[1, 2, 3, 4]

Answer:
python
CopyEdit
def longest_consecutive_sequence(nums):
num_set = set(nums)
longest = []

for num in num_set:


if num - 1 not in num_set:
current = num
temp_sequence = [current]

while current + 1 in num_set:


current += 1
temp_sequence.append(current)

if len(temp_sequence) > len(longest):


longest = temp_sequence

return longest

Explanation in Steps:
1. Convert the list to a set for fast lookups.
2. Loop through each number in the set.
3. If num - 1 is not in the set, it’s the start of a new sequence.

Python Interview Questions Cookbook 39


4. Keep building a temporary sequence while num + 1 , num + 2 , etc. exist.
5. If the current sequence is longer than the previous best, update the result.

Given a string, return the length of the longest


substring without repeating characters.
Example:
python
CopyEdit
s = "abcabcbb"

Expected Output:

python
CopyEdit
3 # "abc"

Answer (Using Sliding Window + Set):


python
CopyEdit
def length_of_longest_substring(s):
seen = set()
left = 0
max_len = 0

for right in range(len(s)):


while s[right] in seen:
[Link](s[left])
left += 1
[Link](s[right])

Python Interview Questions Cookbook 40


max_len = max(max_len, right - left + 1)

return max_len

Explanation in Steps:
1. Use a set ( seen ) to track characters in the current substring.
2. Use two pointers:
left marks the start of the current window.
right expands the window to the right.
3. If the character at right is already in seen , shrink the window from the left
until it’s removed.
4. At each step, update max_len as the length of the current valid window: right -

left + 1 .

Given a list of strings, group the anagrams together


and return a dictionary where the key is the sorted
letter signature, and the value is a list of anagrams.
Example:
python
CopyEdit
words = ["listen", "silent", "enlist", "rat", "tar", "art"]

Expected Output:

python
CopyEdit
{

Python Interview Questions Cookbook 41


'eilnst': ['listen', 'silent', 'enlist'],
'art': ['rat', 'tar', 'art']
}

Answer (Using a Dictionary with Sorted Strings as Keys):


python
CopyEdit
from collections import defaultdict

def group_anagrams(words):
anagrams = defaultdict(list)

for word in words:


key = ''.join(sorted(word))
anagrams[key].append(word)

return dict(anagrams)

Explanation in Steps:
1. Use a defaultdict(list) to automatically initialize empty lists for new keys.
2. For each word:
Sort its letters alphabetically → this forms the anagram signature.
Use that sorted string as a key to group the word.
3. Return the dictionary with each group of anagrams.

Given a string, find the longest palindromic substring.


Example:

Python Interview Questions Cookbook 42


python
CopyEdit
s = "babad"

Expected Output:

python
CopyEdit
"bab" # or "aba", both are valid

Answer (Expand Around Center — O(n²) Time, O(1) Space):


python
CopyEdit
def longest_palindrome(s):
if not s:
return ""

start = 0
end = 0

def expand_around_center(left, right):


while left >= 0 and right < len(s) and s[left] == s[r
ight]:
left -= 1
right += 1
return left + 1, right - 1

for i in range(len(s)):
l1, r1 = expand_around_center(i, i) # odd-lengt
h
l2, r2 = expand_around_center(i, i + 1) # even-leng

Python Interview Questions Cookbook 43


th

if r1 - l1 > end - start:


start, end = l1, r1
if r2 - l2 > end - start:
start, end = l2, r2

return s[start:end + 1]

Explanation in Steps:
1. Loop through each index in the string.
2. At each index, try to expand around a center:
Once for an odd-length palindrome (center at i )
Once for an even-length palindrome (center at i and i + 1 )
3. For each expansion, track the longest bounds ( start , end ) found so far.
4. After the loop, return the substring from start to end .

What is the best way to concatenate n strings into


one in Python?
✅ Best Practice (When You Have a List of Strings):
python
CopyEdit
result = ''.join(list_of_strings)

Why it's the best:


Efficient: It avoids creating intermediate strings during concatenation.

Python Interview Questions Cookbook 44


Performs better than + in a loop, especially when concatenating many strings
( O(n) vs O(n²) in some cases).
Memory-safe: Allocates memory only once.

Example:
python
CopyEdit
words = ["this", "is", "fast"]
sentence = ' '.join(words)
print(sentence) # "this is fast"

🚫 What to Avoid:
python
CopyEdit
# Inefficient for large n
result = ""
for word in words:
result += word

This creates a new string object on every iteration (strings are immutable),
which slows down performance.

Summary:
Method Use When Efficiency
''.join(list) You have a list of strings ✅ Best
str1 + str2 + ... A small, fixed number of strings Fine
+= in loop Many strings, especially in a loop ❌ Avoid

Python Interview Questions Cookbook 45


What is the output of the following code?
python
CopyEdit
a = [[]] * 5
a[0].append(1)
print(a)

Answer:
python
CopyEdit
[[1], [1], [1], [1], [1]]

Explanation in Steps:
1. creates a list with 5 references to the same inner list, not 5
a = [[]] * 5

independent lists.
2. When you do a[0].append(1) , you're modifying the shared list.
3. As a result, all elements in a reflect the same change, because they all point
to the same object.

Visualization:
python
CopyEdit
id(a[0]) == id(a[1]) == id(a[2]) == ... # True

✅ How to create independent sublists:


Python Interview Questions Cookbook 46
python
CopyEdit
a = [[] for _ in range(5)]
a[0].append(1)
print(a) # [[1], [], [], [], []]

What is the output of this expression?


python
CopyEdit
(0, 1, 2, 3, (4, 5, 6), 7, 8)[::3]

Answer:
python
CopyEdit
(0, 3, 7)

Explanation in Steps:
The tuple is:

python
CopyEdit
(0, 1, 2, 3, (4, 5, 6), 7, 8)

Using slice notation [::3] means:


Start from the beginning ( 0 )
Step by 3 — i.e., take every 3rd element

Python Interview Questions Cookbook 47


So, we get:
Index 0 → 0

Index 3 → 3

Index 6 → 7

The final result:

python
CopyEdit
(0, 3, 7)

Note: The tuple (4, 5, 6) at index 4 is skipped because of the stepping.

How do you transpose a square matrix (n x n) in


Python?
That means swapping rows and columns, i.e., turning matrix[i][j] into matrix[j]

[i] .

Example:
Original matrix:

python
CopyEdit
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

Expected transposed matrix:

Python Interview Questions Cookbook 48


python
CopyEdit
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]

Answer 1: Using Nested Loops


python
CopyEdit
def transpose(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix
[i][j]
return matrix

This transposes the matrix in-place (no extra space).


Only swaps elements above the diagonal to avoid reversing the swap.

Answer 2: Using zip() (if creating a new matrix)


python
CopyEdit
def transpose(matrix):
return [list(row) for row in zip(*matrix)]

Python Interview Questions Cookbook 49


This is clean and Pythonic.
It returns a new matrix, not in-place.

Python Interview Questions Cookbook 50

You might also like