Friday, January 17, 2025
HomeProgrammingPython Coding Interview Questions and Answers

Python Coding Interview Questions and Answers

Here are some common Python coding interview questions along with sample answers and explanations to help you prepare for your next interview:

1. Reverse a String

Question: Write a Python function to reverse a string.

Answer:

def reverse_string(s: str) -> str:
    return s[::-1]

Explanation:
The slice notation [::-1] is used to reverse the string. This approach has O(n) time complexity, where n is the length of the string.

2. Check for Palindrome

Question: Write a Python function to check if a string is a palindrome.

Answer:

def is_palindrome(s: str) -> bool:
    s = s.lower().replace(" ", "")  # Remove spaces and convert to lowercase
    return s == s[::-1]

Explanation:
First, we remove spaces and convert the string to lowercase to handle case sensitivity and ignore spaces. Then, we check if the string is the same when reversed.

3. Find the Missing Number in a List

Question: Given a list of integers from 1 to n with one number missing, write a function to find the missing number.

Answer:

def find_missing_number(nums: list) -> int:
    n = len(nums) + 1
    total_sum = n * (n + 1) // 2  # Sum of numbers from 1 to n
    return total_sum - sum(nums)

Explanation:
The sum of integers from 1 to n can be calculated using the formula n * (n + 1) / 2. By subtracting the sum of the numbers in the list from this total, we can find the missing number.

See also  Where and how is the term "wrapper" used?

4. Fibonacci Sequence

Question: Write a Python function to return the nth Fibonacci number.

Answer:

def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n+1):
        a, b = b, a + b
    return b

Explanation:
This approach uses an iterative method to calculate the Fibonacci sequence, which has O(n) time complexity and O(1) space complexity.

5. Find Duplicates in a List

Question: Given a list of integers, write a function to find all duplicates in the list.

Answer:

def find_duplicates(nums: list) -> list:
    seen = set()
    duplicates = []
    for num in nums:
        if num in seen:
            duplicates.append(num)
        else:
            seen.add(num)
    return duplicates

Explanation:
We use a set to track the numbers we’ve seen before. If a number is already in the set, it’s a duplicate, so we add it to the duplicates list.

6. Two Sum Problem

Question: Given a list of integers and a target sum, write a Python function to find two numbers in the list that add up to the target.

Answer:

def two_sum(nums: list, target: int) -> list:
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

Explanation:
We use a dictionary to store the numbers we have seen and their indices. For each number in the list, we check if its complement (the number that would sum to the target) has been seen before. If so, we return the indices.

See also  How can I use a string containing a single quote (') in the SQL IN clause?

7. Find the Largest Element in an Array

Question: Write a Python function to find the largest element in a list.

Answer:

def find_largest(nums: list) -> int:
    return max(nums)

Explanation:
Python provides a built-in max() function that can be used to find the largest element in a list.

8. Count the Occurrences of Each Element

Question: Write a Python function to count how many times each element appears in a list.

Answer:

from collections import Counter

def count_occurrences(nums: list) -> dict:
    return dict(Counter(nums))

Explanation:
The Counter class from Python’s collections module makes it easy to count occurrences of each element in a list and returns a dictionary with the elements as keys and their counts as values.

9. Merge Two Sorted Lists

Question: Given two sorted lists, write a Python function to merge them into one sorted list.

Answer:

def merge_sorted_lists(list1: list, list2: list) -> list:
    merged = []
    i, j = 0, 0
    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1
    merged.extend(list1[i:])
    merged.extend(list2[j:])
    return merged

Explanation:
We use a two-pointer technique to merge the lists. We compare elements from both lists, adding the smaller element to the result. After one list is exhausted, we append the remaining elements from the other list.

See also  Passing a JavaScript Function as a Parameter

10. Remove Duplicates from a Sorted List

Question: Write a function to remove duplicates from a sorted list.

Answer:

def remove_duplicates(nums: list) -> list:
    if not nums:
        return []
    result = [nums[0]]
    for i in range(1, len(nums)):
        if nums[i] != nums[i - 1]:
            result.append(nums[i])
    return result

Explanation:
Since the list is sorted, we can check adjacent elements. If an element is different from the previous one, we add it to the result list.

These are just some common examples of coding problems you may encounter in Python interviews. It’s important to practice these and think about the time and space complexities of your solutions, as these are often discussed during interviews.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x