Wednesday, April 30, 2025

Python coding interview questions sample set 1

 

Here’s a curated list of Python coding interview questions categorized by difficulty, along with solutions and explanations:


🌱 Beginner Level (Basic Syntax & Logic)

1. FizzBuzz

Problem: Print numbers 1-100. For multiples of 3, print "Fizz"; for multiples of 5, print "Buzz"; for both, print "FizzBuzz".
Solution:

python
Copy
Download
for i in range(1, 101):
    output = ""
    if i % 3 == 0: output += "Fizz"
    if i % 5 == 0: output += "Buzz"
    print(output or i)

Key Concept: Conditional logic and string concatenation.


2. Reverse a String

Problem: Reverse a string without built-in functions.
Solution:

python
Copy
Download
def reverse_string(s):
    return s[::-1]  # Slice with step -1

Optimization: O(n) time, O(1) space.


📊 Intermediate Level (Data Structures & Algorithms)

3. Two Sum

Problem: Given an array and a target, return indices of two numbers that add up to the target.
Solution:

python
Copy
Download
def two_sum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

Key Concept: Hash map for O(n) time complexity.


4. Validate Palindrome

Problem: Check if a string is a palindrome (ignoring non-alphanumeric chars).
Solution:

python
Copy
Download
import re
def is_palindrome(s):
    s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
    return s == s[::-1]

Optimization: Regex for cleaning input.


🚀 Advanced Level (Optimization & System Design)

5. LRU Cache

Problem: Design a Least Recently Used (LRU) cache.
Solution:

python
Copy
Download
from collections import OrderedDict
class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key):
        if key not in self.cache: return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, value):
        if key in self.cache: self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity: self.cache.popitem(last=False)

Key Concept: OrderedDict maintains insertion order.


6. Multithreaded Web Scraper

Problem: Fetch URLs concurrently with threading.
Solution:

python
Copy
Download
import threading
import requests

def fetch_url(url):
    response = requests.get(url)
    print(f"{url}: {len(response.content)} bytes")

threads = []
urls = ["https://example.com", "https://google.com"]
for url in urls:
    t = threading.Thread(target=fetch_url, args=(url,))
    t.start()
    threads.append(t)
for t in threads: t.join()

Note: Use ThreadPoolExecutor for better scalability.


🧠 Problem-Solving Patterns

7. Sliding Window (Max Subarray)

Problem: Find the maximum sum of a subarray of size k.
Solution:

python
Copy
Download
def max_subarray(nums, k):
    window_sum = max_sum = sum(nums[:k])
    for i in range(k, len(nums)):
        window_sum += nums[i] - nums[i - k]
        max_sum = max(max_sum, window_sum)
    return max_sum

Pattern: Fixed-size window optimization.


8. Backtracking (Permutations)

Problem: Generate all permutations of a list.
Solution:

python
Copy
Download
def permute(nums):
    def backtrack(path, remaining):
        if not remaining: res.append(path)
        for i in range(len(remaining)):
            backtrack(path + [remaining[i]], remaining[:i] + remaining[i+1:])
    res = []
    backtrack([], nums)
    return res

Key Concept: Recursive tree traversal.


🔍 Real-World Scenarios

9. Parse JSON Log Files

Problem: Extract error messages from logs.
Solution:

python
Copy
Download
import json
def parse_errors(log_file):
    errors = []
    with open(log_file) as f:
        for line in f:
            log = json.loads(line)
            if log["level"] == "ERROR":
                errors.append(log["message"])
    return errors

Library: json module for serialization.


10. Design a Rate Limiter

Problem: Allow 100 requests/minute per user.
Solution:

python
Copy
Download
from collections import defaultdict
from time import time

class RateLimiter:
    def __init__(self):
        self.requests = defaultdict(list)

    def allow_request(self, user_id):
        now = time()
        self.requests[user_id] = [t for t in self.requests[user_id] if t > now - 60]
        if len(self.requests[user_id]) < 100:
            self.requests[user_id].append(now)
            return True
        return False

Algorithm: Sliding window counter.


📌 Quick Reference Table

CategorySample Questions
StringsAnagram check, Longest substring
ArraysRotate matrix, Merge intervals
GraphsBFS/DFS, Dijkstra’s algorithm
Dynamic Prog.Fibonacci, Knapsack problem
OOPDesign parking lot, Singleton pattern

💡 Pro Tips:

  1. Always clarify input constraints (e.g., "Can the array be empty?").

  2. Test edge cases (empty input, large numbers).

  3. Explain your approach before coding.

Practice Platforms:

Thanks
SK Institute
www.skgov.in
Learn with us

No comments:

Post a Comment