1. Factorial CalculationProblem StatementWrite a function to calculate the factorial of a number n using recursion.ApproachFactorial of n is n * factorial(n-1). Base case is when n = 0 or 1, return 1.Solutiondef factorial(n): if n <= 1: return 1 return n * factorial(n - 1) print(factorial(5)) # 120
2. Fibonacci SequenceProblem StatementWrite a function to return the nth Fibonacci number using recursion.ApproachFibonacci: F(n) = F(n-1) + F(n-2). Base cases: F(0) = 0, F(1) = 1.Solutiondef fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(7)) # 13
3. Sum of ListProblem StatementWrite a function that calculates the sum of all numbers in a list.ApproachIterate through the list and add each element to a running total.Solutiondef sum_list(numbers): total = 0 for num in numbers: total += num return total print(sum_list([1, 2, 3, 4, 5])) # 15
4. Find MinimumProblem StatementWrite a function to find the minimum value in a list without using the min() function.ApproachInitialize min_val with the first element, then iterate and update if you find a smaller value.Solutiondef find_min(numbers): min_val = numbers[0] for num in numbers: if num < min_val: min_val = num return min_val print(find_min([5, 2, 8, 1, 9])) # 1
5. Palindrome CheckProblem StatementWrite a function to check if a string is a palindrome (reads the same forwards and backwards).ApproachCompare the string with its reverse. Use slicing [::-1] to reverse.Solutiondef is_palindrome(text): return text == text[::-1] print(is_palindrome("racecar")) # True print(is_palindrome("hello")) # False
6. Count VowelsProblem StatementWrite a function to count the number of vowels in a string.ApproachIterate through the string and check if each character is in the vowels set.Solutiondef count_vowels(text): vowels = "aeiouAEIOU" count = 0 for char in text: if char in vowels: count += 1 return count print(count_vowels("Hello World")) # 3
7. Reverse a StringProblem StatementWrite a function to reverse a string without using slicing.ApproachIterate through the string backwards and build a new string.Solutiondef reverse_string(text): result = "" for i in range(len(text) - 1, -1, -1): result += text[i] return result print(reverse_string("Python")) # nohtyP
8. Prime Number CheckProblem StatementWrite a function to check if a number is prime.ApproachA prime number is only divisible by 1 and itself. Check divisibility from 2 to sqrt(n).Solutiondef is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True print(is_prime(17)) # True print(is_prime(10)) # False
9. Binary SearchProblem StatementImplement binary search to find an element in a sorted list. Return the index or -1 if not found.ApproachCompare the middle element. If equal, return index. If target is smaller, search left half, else right half.Solutiondef 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 print(binary_search([1, 3, 5, 7, 9], 5)) # 2
10. Bubble SortProblem StatementImplement the bubble sort algorithm to sort a list in ascending order.ApproachRepeatedly swap adjacent elements if they're in wrong order. Continue until no swaps needed.Solutiondef bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr print(bubble_sort([64, 34, 25, 12, 22])) # [12, 22, 25, 34, 64]
11. Find DuplicatesProblem StatementWrite a function to find all duplicate elements in a list.ApproachUse a set to track seen elements. If an element is already in the set, it's a duplicate.Solutiondef find_duplicates(arr): seen = set() duplicates = set() for num in arr: if num in seen: duplicates.add(num) seen.add(num) return list(duplicates) print(find_duplicates([1, 2, 3, 2, 4, 5, 1])) # [1, 2]
12. Two Sum ProblemProblem StatementGiven a list of integers and a target sum, find two numbers that add up to the target. Return their indices.ApproachUse a dictionary to store numbers and their indices. For each number, check if (target - number) exists in the dict.Solution`def two_sum(nums, target): seen = {
13. Anagram CheckProblem StatementWrite a function to check if two strings are anagrams (contain the same characters in different order).ApproachSort both strings and compare, or count character frequencies.Solutiondef is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) print(is_anagram("listen", "silent")) # True print(is_anagram("hello", "world")) # False
14. Remove Duplicates from Sorted ListProblem StatementRemove duplicates from a sorted list in-place and return the new length.ApproachUse two pointers. One for the unique position, one for scanning.Solutiondef remove_duplicates(nums): if not nums: return 0 i = 0 for j in range(1, len(nums)): if nums[j] != nums[i]: i += 1 nums[i] = nums[j] return i + 1 arr = [1, 1, 2, 2, 3, 4, 4] length = remove_duplicates(arr) print(arr[:length]) # [1, 2, 3, 4]
15. Merge Two Sorted ListsProblem StatementMerge two sorted lists into one sorted list.ApproachUse two pointers to compare elements from both lists and build the result.Solutiondef merge_sorted(list1, list2): result = [] i, j = 0, 0 while i < len(list1) and j < len(list2): if list1[i] < list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 result.extend(list1[i:]) result.extend(list2[j:]) return result print(merge_sorted([1, 3, 5], [2, 4, 6])) # [1, 2, 3, 4, 5, 6]
16. GCD (Greatest Common Divisor)Problem StatementWrite a function to find the GCD of two numbers using Euclidean algorithm.ApproachGCD(a, b) = GCD(b, a % b). Base case: when b = 0, return a.Solutiondef gcd(a, b): while b: a, b = b, a % b return a print(gcd(48, 18)) # 6
17. Power FunctionProblem StatementImplement a function to calculate x raised to power n without using the ** operator.ApproachUse recursion or iteration. For recursion: power(x, n) = x * power(x, n-1).Solutiondef power(x, n): if n == 0: return 1 if n < 0: return 1 / power(x, -n) return x * power(x, n - 1) print(power(2, 5)) # 32
18. Rotate ArrayProblem StatementRotate an array to the right by k steps. For example, [1,2,3,4,5] rotated by 2 becomes [4,5,1,2,3].ApproachUse slicing: arr[-k:] + arr[:-k]. Handle k > len(arr) by using k % len(arr).Solutiondef rotate_array(arr, k): k = k % len(arr) return arr[-k:] + arr[:-k] print(rotate_array([1, 2, 3, 4, 5], 2)) # [4, 5, 1, 2, 3]
19. Longest Common PrefixProblem StatementFind the longest common prefix among an array of strings.ApproachCompare characters at each position across all strings until a mismatch is found.Solutiondef 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 print(longest_common_prefix(["flower", "flow", "flight"])) # "fl"
20. Valid ParenthesesProblem Statement`Check if a string containing only '(', ')', '{', 'ApproachUse a stack. Push opening brackets, pop when you see closing brackets. Check if they match.Solution`def is_valid_parentheses(s): stack = [] mapping = {')': '(', '