Python Quetions
Python Quetions
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
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
Interview Caution:
If the interviewer cares about order preservation or duplicates, this solution is
not valid. Otherwise, it's a great one-liner.
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]
not in Y .
python
CopyEdit
X = [2, 5, 1, 2, 3, 5]
Expected Output:
python
CopyEdit
2
Answer:
python
CopyEdit
def first_duplicate(X):
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 .
python
CopyEdit
X = [1, [2, [3, 4], 5], 6]
Expected Output:
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.
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
CopyEdit
X = [1, 2, 2, 3, 1, 4]
Expected Output:
python
CopyEdit
[1, 2, 3, 4]
Answer:
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.
python
CopyEdit
X = [4, 5, 2, 4, 3, 5, 4]
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
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
CopyEdit
X = [1, 2, 3, 1, 3, 6, 5]
Expected Output:
python
CopyEdit
[1, 3]
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.
python
CopyEdit
Expected Output:
python
CopyEdit
300 # 10 * 6 * 5
python
CopyEdit
X = [-10, -10, 1, 3, 2]
Expected Output:
python
CopyEdit
300 # (-10) * (-10) * 3
Explanation in Steps:
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.
python
CopyEdit
A = [0, -1, -5, -2, 3, 14]
Expected Output:
python
CopyEdit
17 # from subarray [3, 14]
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
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.
python
CopyEdit
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
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.
python
CopyEdit
A = [1, 2, 5, -7, 2, 3]
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
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.
python
CopyEdit
my_list = [1, 2, 3]
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:
# 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.
python
CopyEdit
X = [1, 2, 3]
Y = [4, 0, 3]
Expected Output:
python
CopyEdit
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]() .
python
CopyEdit
n = 3
k = 2
Expected Output:
python
CopyEdit
[[1, 2], [1, 3], [2, 3]]
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
CopyEdit
def combine(n, k):
result = []
backtrack(1, [])
return result
Example:
python
CopyEdit
n = 3
k = 2
python
CopyEdit
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
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
Expected Output:
python
CopyEdit
[[2, 4], [2, 6], [4, 6]]
Answer:
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.
Answer:
python
CopyEdit
def longest_increasing_path(matrix):
if not matrix or not matrix[0]:
return 0
memo[r][c] = max_length
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.
python
CopyEdit
my_list = [1, 2, 3, 2]
When to Use:
Use lists when:
You need to preserve order
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
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
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 .
Expected Output:
python
CopyEdit
2
# Example
print(count_char_occurrences("programming", "m")) # Output:
2
python
CopyEdit
text = "Programming"
char = "m"
Answer:
python
CopyEdit
def find_middle(lst):
n = len(lst)
mid = n // 2
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] .
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")
Even though we tried to instantiate it twice, both a and b are the same object.
Expected Output:
python
CopyEdit
4 # The sequence is [1, 2, 3, 4]
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.
Example:
python
CopyEdit
nums = [100, 4, 200, 1, 3, 2]
Expected Output:
Answer:
python
CopyEdit
def longest_consecutive_sequence(nums):
num_set = set(nums)
longest = []
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.
Expected Output:
python
CopyEdit
3 # "abc"
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 .
Expected Output:
python
CopyEdit
{
def group_anagrams(words):
anagrams = defaultdict(list)
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.
Expected Output:
python
CopyEdit
"bab" # or "aba", both are valid
start = 0
end = 0
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
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 .
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
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
Answer:
python
CopyEdit
(0, 3, 7)
Explanation in Steps:
The tuple is:
python
CopyEdit
(0, 1, 2, 3, (4, 5, 6), 7, 8)
Index 3 → 3
Index 6 → 7
python
CopyEdit
(0, 3, 7)
[i] .
Example:
Original matrix:
python
CopyEdit
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]