Common Python Coding Problems — Part 2

CodeyMaze
2 min readDec 27, 2024

--

In this article, we will solve some common coding problems in Python. You can use this list to practice interview questions.

Find Duplicates in a List -Python

def find_duplicates(lst):
seen = set()
duplicates = set()

for x in lst:
if x in seen:
duplicates.add(x)
else:
seen.add(x)

return list(duplicates)

# Example usage
duplicates = find_duplicates([1, 2, 3, 1, 2, 4])
print(duplicates) # Output: [1, 2]

Valid Parentheses Problem — Python

def is_balanced(s):
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for char in s:
if char in pairs.values():
stack.append(char)
elif char in pairs.keys():
if not stack or stack.pop() != pairs[char]:
return False
return not stack

# Example usage
print(is_balanced("({[]})")) # True
print(is_balanced("({[)]}")) # False

Finding the Largest and Smallest Numbers in a List — Python

def find_max_min(numbers):
max_num = min_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
elif num < min_num:
min_num = num
return max_num, min_num

# Example usage
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_value, min_value = find_max_min(numbers)
print("Max:", max_value, "Min:", min_value)

Matrix Multiplication — Python

import numpy as np

def matrix_multiply(A, B):
return np.dot(A, B)

# Example usage
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = matrix_multiply(A, B)
print(result)

Prime Number Checker — Python

def is_prime(n):
return n > 1 and all(n % i for i in range(2, int(n**0.5) + 1))

def primes_up_to(N):
return [x for x in range(2, N + 1) if is_prime(x)]

# Example usage
number = 29
print(f"{number} is prime: {is_prime(number)}")
print("Primes up to 30:", primes_up_to(30))

Longest Substring Without Repeating Characters — Python

def length_of_longest_substring(s: str) -> int:
char_map, left, max_length = {}, 0, 0
for right, char in enumerate(s):
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
max_length = max(max_length, right - left + 1)
return max_length

# Example usage
print(length_of_longest_substring("abcabcbb")) # Output: 3

Merge Two Sorted Lists — Python

def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0

while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1

# Append any remaining elements
merged_list.extend(list1[i:])
merged_list.extend(list2[j:])

return merged_list

# Example
result = merge_sorted_lists([1, 3, 5], [2, 4, 6])
print(result) # Output: [1, 2, 3, 4, 5, 6]

Click here to view more problems like this!

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet