[2024] Python Coding Challenges for Interviews

Prepare for your Python coding interviews with a range of practical coding challenges. This guide features problems from basic string manipulation to advanced algorithms, complete with solutions to help you enhance your problem-solving skills and improve your interview readiness. Perfect for candidates looking to strengthen their Python proficiency before their next interview.

[2024] Python Coding Challenges for Interviews

Python is a powerful programming language widely used in coding interviews for various roles, particularly in software development and data science. Preparing for coding interviews often involves solving practical coding challenges that test problem-solving skills, algorithmic thinking, and Python proficiency. Here’s a collection of Python coding challenges that are commonly encountered in interviews, complete with explanations and solutions.

1. Reverse a String

Challenge: Write a Python function to reverse a string.

Solution:

def reverse_string(s): return s[::-1] # Example usage print(reverse_string("interview")) # Output: "weivretni"

2. Check for Palindrome

Challenge: Determine if a given string is a palindrome (reads the same forwards and backwards).

Solution:

def is_palindrome(s): return s == s[::-1] # Example usage print(is_palindrome("radar")) # Output: True print(is_palindrome("python")) # Output: False

3. Find the Largest Element in a List

Challenge: Find the largest element in a list of integers.

Solution:

def find_largest_element(lst): return max(lst) # Example usage print(find_largest_element([3, 5, 7, 2, 8])) # Output: 8

4. FizzBuzz Problem

Challenge: Print numbers from 1 to 100. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For numbers that are multiples of both 3 and 5, print "FizzBuzz".

Solution:

def fizz_buzz(): for i in range(1, 101): if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) # Example usage fizz_buzz()

5. Count Occurrences of a Character in a String

Challenge: Count the number of times a specific character appears in a string.

Solution:

def count_char_occurrences(s, char): return s.count(char) # Example usage print(count_char_occurrences("programming", "g")) # Output: 2

6. Merge Two Sorted Lists

Challenge: Merge two sorted lists into a single sorted list.

Solution:

def merge_sorted_lists(list1, list2): return sorted(list1 + list2) # Example usage print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]

7. Find the Fibonacci Sequence

Challenge: Generate the first n numbers in the Fibonacci sequence.

Solution:

def fibonacci(n): sequence = [0, 1] while len(sequence) < n: sequence.append(sequence[-1] + sequence[-2]) return sequence # Example usage print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

8. Sum of Digits in a Number

Challenge: Calculate the sum of digits of a given number.

Solution:

def sum_of_digits(n): return sum(int(digit) for digit in str(n)) # Example usage print(sum_of_digits(1234)) # Output: 10

9. Find the Factorial of a Number

Challenge: Compute the factorial of a given number.

Solution:

def factorial(n): if n == 0: return 1 return n * factorial(n - 1) # Example usage print(factorial(5)) # Output: 120

10. Remove Duplicates from a List

Challenge: Remove duplicates from a list while maintaining the original order of elements.

Solution:

def remove_duplicates(lst): return list(dict.fromkeys(lst)) # Example usage print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]

11. Find the Intersection of Two Lists

Challenge: Find the common elements between two lists.

Solution:

def intersect_lists(list1, list2): return list(set(list1) & set(list2)) # Example usage print(intersect_lists([1, 2, 3, 4], [3, 4, 5, 6])) # Output: [3, 4]

12. Check for Anagrams

Challenge: Determine if two strings are anagrams of each other (contain the same characters in any order).

Solution:

def are_anagrams(s1, s2): return sorted(s1) == sorted(s2) # Example usage print(are_anagrams("listen", "silent")) # Output: True print(are_anagrams("hello", "world")) # Output: False

13. Find the Missing Number in a Sequence

Challenge: Given a list of n-1 numbers from 1 to n, find the missing number.

Solution:

def find_missing_number(lst, n): total_sum = n * (n + 1) // 2 return total_sum - sum(lst) # Example usage print(find_missing_number([1, 2, 4, 5, 6], 6)) # Output: 3

14. Rotate a List

Challenge: Rotate a list to the right by k steps.

Solution:

def rotate_list(lst, k): k %= len(lst) return lst[-k:] + lst[:-k] # Example usage print(rotate_list([1, 2, 3, 4, 5], 2)) # Output: [4, 5, 1, 2, 3]

15. Find the Unique Element in a List

Challenge: Find the element that appears only once in a list where all other elements appear twice.

Solution:

def find_unique(lst): unique = 0 for num in lst: unique ^= num return unique # Example usage print(find_unique([1, 2, 3, 2, 1])) # Output: 3

16. Check if Two Strings are Rotations of Each Other

Challenge: Check if one string is a rotation of another string.

Solution:

def are_rotations(s1, s2): return len(s1) == len(s2) and s2 in (s1 + s1) # Example usage print(are_rotations("waterbottle", "erbottlewat")) # Output: True print(are_rotations("hello", "olelh")) # Output: False

17. Generate Pascal’s Triangle

Challenge: Generate the first n rows of Pascal’s Triangle.

Solution:

def generate_pascals_triangle(n): triangle = [[1]] for i in range(1, n): row = [1] for j in range(1, i): row.append(triangle[i-1][j-1] + triangle[i-1][j]) row.append(1) triangle.append(row) return triangle # Example usage print(generate_pascals_triangle(5))

18. Count Vowels in a String

Challenge: Count the number of vowels in a given string.

Solution:

def count_vowels(s): return sum(1 for char in s if char.lower() in 'aeiou') # Example usage print(count_vowels("Hello World")) # Output: 3

19. Convert a String to Title Case

Challenge: Convert a string to title case, where the first letter of each word is capitalized.

Solution:

def to_title_case(s): return s.title() # Example usage print(to_title_case("hello world")) # Output: "Hello World"

20. Find All Permutations of a String

Challenge: Generate all permutations of a given string.

Solution:

from itertools import permutations def find_permutations(s): return [''.join(p) for p in permutations(s)] # Example usage print(find_permutations("abc")) # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

21. Find the Longest Substring Without Repeating Characters

Challenge: Find the length of the longest substring without repeating characters.

Solution:

def longest_substring_without_repeating(s): start = 0 max_length = 0 used_chars = {} for end in range(len(s)): if s[end] in used_chars and used_chars[s[end]] >= start: start = used_chars[s[end]] + 1 used_chars[s[end]] = end max_length = max(max_length, end - start + 1) return max_length # Example usage print(longest_substring_without_repeating("abcabcbb")) # Output: 3

22. Merge Intervals

Challenge: Merge overlapping intervals in a list of intervals.

Solution:

def merge_intervals(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last_merged = merged[-1] if current[0] <= last_merged[1]: last_merged[1] = max(last_merged[1], current[1]) else: merged.append(current) return merged # Example usage print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])) # Output: [[1, 6], [8, 10], [15, 18]]

23. Find the kth Largest Element in an Array

Challenge: Find the kth largest element in an unsorted list of integers.

Solution:

import heapq def kth_largest_element(nums, k): return heapq.nlargest(k, nums)[-1] # Example usage print(kth_largest_element([3, 2, 1, 5, 6, 4], 2)) # Output: 5

24. Check if a Number is a Prime

Challenge: Determine if a given number is a prime number.

Solution:

def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True # Example usage print(is_prime(29)) # Output: True print(is_prime(18)) # Output: False

25. Rotate a Matrix 90 Degrees

Challenge: Rotate an NxN matrix 90 degrees clockwise.

Solution:

def rotate_matrix(matrix): return [list(row) for row in zip(*matrix[::-1])] # Example usage matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(rotate_matrix(matrix)) # Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

26. Find the Minimum Window Substring

Challenge: Find the smallest window in a string that contains all the characters of another string.

Solution:

from collections import Counter def min_window(s, t): if not t or not s: return "" dict_t = Counter(t) required = len(dict_t) l, r = 0, 0 formed = 0 window_counts = {} ans = float("inf"), None, None while r < len(s): character = s[r] window_counts[character] = window_counts.get(character, 0) + 1 if character in dict_t and window_counts[character] == dict_t[character]: formed += 1 while l <= r and formed == required: character = s[l] if r - l + 1 < ans[0]: ans = (r - l + 1, l, r) window_counts[character] -= 1 if character in dict_t and window_counts[character] < dict_t[character]: formed -= 1 l += 1 r += 1 return "" if ans[0] == float("inf") else s[ans[1]: ans[2] + 1] # Example usage print(min_window("ADOBECODEBANC", "ABC")) # Output: "BANC"

27. Longest Common Prefix

Challenge: Find the longest common prefix string among an array of strings.

Solution:

def longest_common_prefix(strs): if not strs: return "" prefix = strs[0] for s in strs[1:]: while not s.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix # Example usage print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"

28. Search in Rotated Sorted Array

Challenge: Search for a target value in a rotated sorted array.

Solution:

def search_rotated_array(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid if nums[left] <= nums[mid]: if nums[left] <= target < nums[mid]: right = mid - 1 else: left = mid + 1 else: if nums[mid] < target <= nums[right]: left = mid + 1 else: right = mid - 1 return -1 # Example usage print(search_rotated_array([4, 5, 6, 7, 0, 1, 2], 0)) # Output: 4

29. Implement Binary Search

Challenge: Implement a binary search algorithm to find the position of a target value in a sorted list.

Solution:

def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # Example usage print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2

30. Find Missing Positive Integer

Challenge: Find the smallest positive integer that is missing from an unsorted list.

Solution:

def first_missing_positive(nums): nums = set(nums) i = 1 while i in nums: i += 1 return i # Example usage print(first_missing_positive([3, 4, -1, 1])) # Output: 2

31. Check for Balanced Parentheses

Challenge: Check if a string has balanced parentheses.

Solution:

def is_balanced_parentheses(s): stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if char in mapping: top_element = stack.pop() if stack else '#' if mapping[char] != top_element: return False else: stack.append(char) return not stack # Example usage print(is_balanced_parentheses("{[()]}")) # Output: True print(is_balanced_parentheses("{[(])}")) # Output: False

32. Calculate Power of a Number

Challenge: Calculate the power of a number using recursion.

Solution:

def power(x, n): if n == 0: return 1 if n % 2 == 0: half_power = power(x, n // 2) return half_power * half_power else: return x * power(x, n - 1) # Example usage print(power(2, 10)) # Output: 1024

33. Check if a Number is a Perfect Square

Challenge: Determine if a given number is a perfect square.

Solution:

import math def is_perfect_square(num): if num < 0: return False root = int(math.sqrt(num)) return root * root == num # Example usage print(is_perfect_square(16)) # Output: True print(is_perfect_square(14)) # Output: False

34. Find the Sum of the Digits of a Number

Challenge: Calculate the sum of the digits of a given number.

Solution:

def sum_of_digits(n): return sum(int(digit) for digit in str(n)) # Example usage print(sum_of_digits(1234)) # Output: 10

35. Generate a List of Fibonacci Numbers

Challenge: Generate the first n Fibonacci numbers.

Solution:

def fibonacci(n): fib_seq = [0, 1] while len(fib_seq) < n: fib_seq.append(fib_seq[-1] + fib_seq[-2]) return fib_seq[:n] # Example usage print(fibonacci(7)) # Output: [0, 1, 1, 2, 3, 5, 8]

36. Count Inversions in an Array

Challenge: Count the number of inversions in an array (where an inversion is a pair of indices (i, j) such that i < j and arr[i] > arr[j]).

Solution:

def count_inversions(arr): def merge_count_split_inv(arr, temp_arr, left, mid, right): i = left # Starting index for left subarray j = mid + 1 # Starting index for right subarray k = left # Starting index to be sorted inv_count = 0 while i <= mid and j <= right: if arr[i] <= arr[j]: temp_arr[k] = arr[i] i += 1 else: temp_arr[k] = arr[j] inv_count += (mid-i + 1) j += 1 k += 1 while i <= mid: temp_arr[k] = arr[i] i += 1 k += 1 while j <= right: temp_arr[k] = arr[j] j += 1 k += 1 for i in range(left, right + 1): arr[i] = temp_arr[i] return inv_count def merge_sort_and_count(arr, temp_arr, left, right): inv_count = 0 if left < right: mid = (left + right) // 2 inv_count += merge_sort_and_count(arr, temp_arr, left, mid) inv_count += merge_sort_and_count(arr, temp_arr, mid + 1, right) inv_count += merge_count_split_inv(arr, temp_arr, left, mid, right) return inv_count temp_arr = [0]*len(arr) return merge_sort_and_count(arr, temp_arr, 0, len(arr) - 1) # Example usage print(count_inversions([1, 20, 6, 4, 5])) # Output: 5

37. Find the Median of Two Sorted Arrays

Challenge: Find the median of two sorted arrays.

Solution:

def find_median_sorted_arrays(nums1, nums2): nums = sorted(nums1 + nums2) n = len(nums) if n % 2 == 1: return nums[n // 2] else: return (nums[n // 2 - 1] + nums[n // 2]) / 2 # Example usage print(find_median_sorted_arrays([1, 3], [2])) # Output: 2 print(find_median_sorted_arrays([1, 2], [3, 4])) # Output: 2.5

38. Find the Longest Palindromic Substring

Challenge: Find the longest palindromic substring in a given string.

Solution:

def longest_palindromic_substring(s): def expand_from_center(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right] longest = "" for i in range(len(s)): # Odd length palindromes pal1 = expand_from_center(i, i) # Even length palindromes pal2 = expand_from_center(i, i + 1) longest = max(longest, pal1, pal2, key=len) return longest # Example usage print(longest_palindromic_substring("babad")) # Output: "bab" or "aba"

39. Reverse Words in a String

Challenge: Reverse the words in a given string.

Solution:

def reverse_words(s): return ' '.join(s.split()[::-1]) # Example usage print(reverse_words("the sky is blue")) # Output: "blue is sky the"

40. Detect a Cycle in a Linked List

Challenge: Detect if a cycle exists in a linked list.

Solution:

class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False # Example usage node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node2 # Creates a cycle print(has_cycle(node1)) # Output: True

Conclusion

Tackling Python coding challenges is an excellent way to prepare for technical interviews and sharpen your programming skills. This collection of challenges spans a wide range of topics and difficulty levels, ensuring a comprehensive practice experience. By mastering these problems, you’ll enhance your problem-solving abilities and improve your confidence in handling Python coding interviews. Keep practicing and refining your skills to excel in your next interview

These coding challenges are designed to test various aspects of Python programming, including string manipulation, list operations, and algorithmic thinking. Practicing these problems will help you improve your coding skills and prepare effectively for technical interviews. By mastering these challenges, you'll build a strong foundation for tackling more complex problems and succeeding in your Python coding interviews.