Algorithmic Problem Solving in Python (LeetCode)

অ্যালগরিদম — Python-এ LeetCode / কোডিং ইন্টারভিউ কৌশল

Read: ~40 min Advanced 5 practice problems Live code runner

1. Why Python for Interviews?

Python's concise syntax, rich built-ins, and clean data structures give you a real edge in timed interviews. A binary search or heap solution that is 30 lines in Java is 10 lines in Python. Most FAANG-style interviews accept Python; problems designed for C/C++ sometimes have tighter time limits, but you can still pass them by using the right algorithm.

Python-এর সংক্ষিপ্ত সিনট্যাক্স, সমৃদ্ধ built-in, ও পরিচ্ছন্ন data structure — সময়সীমার interview-এ বড় সুবিধা দেয়। Java-তে ৩০ লাইনের binary search বা heap Python-এ ১০ লাইনে লেখা যায়। বেশির ভাগ interview Python গ্রহণ করে; C/C++-এর জন্য ডিজাইন করা সমস্যায় কখনো কখনো time limit কড়া হয়, সঠিক অ্যালগরিদম দিয়ে সেটিও পাস করা যায়।

2. Pattern 1 — Two Pointers

Use two indices moving through an array — often reducing O(n²) brute force to O(n).

two_ptr.py
# Given a sorted array, find if two numbers sum to target.
def two_sum_sorted(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return (lo, hi)
        elif s < target:
            lo += 1
        else:
            hi -= 1
    return None

print(two_sum_sorted([1, 3, 5, 7, 11], 10))

3. Pattern 2 — Sliding Window

window.py
# Longest substring without repeating characters — O(n)
def longest_unique(s):
    seen = {}
    best = start = 0
    for i, ch in enumerate(s):
        if ch in seen and seen[ch] >= start:
            start = seen[ch] + 1
        seen[ch] = i
        best = max(best, i - start + 1)
    return best

print(longest_unique("abcabcbb"))

4. Pattern 3 — BFS / DFS

bfs_dfs.py
from collections import deque

graph = {
    "A": ["B", "C"],
    "B": ["D"],
    "C": ["D", "E"],
    "D": [],
    "E": [],
}

def bfs(start):
    seen, q, order = {start}, deque([start]), []
    while q:
        node = q.popleft()
        order.append(node)
        for nb in graph[node]:
            if nb not in seen:
                seen.add(nb)
                q.append(nb)
    return order

def dfs(node, seen=None, order=None):
    if seen is None:
        seen, order = set(), []
    seen.add(node); order.append(node)
    for nb in graph[node]:
        if nb not in seen:
            dfs(nb, seen, order)
    return order

print("BFS:", bfs("A"))
print("DFS:", dfs("A"))

5. Pattern 4 — Heap / Priority Queue (heapq)

heap.py
import heapq

# Find k smallest
nums = [5, 3, 9, 1, 7, 2, 8]
print(heapq.nsmallest(3, nums))
print(heapq.nlargest(3, nums))

# Median-of-stream idea (min-heap for upper half)
h = []
for n in [4, 1, 7, 2, 9, 3]:
    heapq.heappush(h, n)
print(sorted([heapq.heappop(h) for _ in range(len(h))]))

6. Pattern 5 — Dynamic Programming

dp.py
from functools import lru_cache

# Coin change — minimum coins to make amount
def min_coins(coins, amount):
    @lru_cache
    def solve(a):
        if a == 0: return 0
        if a < 0: return float("inf")
        return 1 + min(solve(a - c) for c in coins)

    r = solve(amount)
    return r if r != float("inf") else -1

print(min_coins((1, 5, 10, 25), 63))

7. Interview Strategy

  • Clarify before coding — inputs, edge cases, constraints, expected complexity.
  • Think out loud — interviewers score communication as much as code.
  • Start with brute force, then refine. A correct O(n²) beats a broken O(n).
  • Know the 5 patterns above — 80% of interviews are variations.
  • Trust Python's stdlib — sorted, bisect, heapq, Counter, deque.
  • Test mentally with 1–2 examples before declaring done.

8. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
Brute forceThe simplest, usually slowest solution.সবচেয়ে সহজ, সাধারণত ধীর সমাধান।
Two pointersTwo indices scanning an array.Array-এ একসাথে দুটি index চলে।
Sliding windowA moving subarray/range.চলমান subarray/range।
MemoizationCaching results (lru_cache).ফলাফল cache করা।
Priority queueQueue ordered by priority (heapq).Priority-ভিত্তিক queue।

9. Practice Problems

  1. Two Sum (unsorted): return indices of two numbers that add up to target.
    Unsorted array থেকে দুটি সংখ্যার index বের করুন যাদের যোগফল target।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    def two_sum(nums, target):
        seen = {}
        for i, x in enumerate(nums):
            if target - x in seen:
                return (seen[target - x], i)
            seen[x] = i
    
    print(two_sum([3, 7, 1, 8], 9))
  2. Reverse a linked list (simulate with a list of nodes).
    Linked list reverse করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    class Node:
        def __init__(self, v, n=None):
            self.val, self.next = v, n
    
    def reverse(head):
        prev = None
        while head:
            head.next, prev, head = prev, head, head.next
        return prev
    
    def to_list(head):
        out = []
        while head:
            out.append(head.val); head = head.next
        return out
    
    head = Node(1, Node(2, Node(3, Node(4))))
    print(to_list(reverse(head)))
  3. Find the k-th largest element in a list using heapq.
    heapq দিয়ে k-তম বৃহত্তম সংখ্যা বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    import heapq
    def kth_largest(nums, k):
        return heapq.nlargest(k, nums)[-1]
    
    print(kth_largest([3, 1, 4, 1, 5, 9, 2, 6], 3))
  4. Given a string, check if it's a valid palindrome ignoring non-alphanumeric and case.
    Non-alphanumeric ও case ignore করে palindrome check করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans4.py
    def is_palindrome(s):
        t = [c.lower() for c in s if c.isalnum()]
        return t == t[::-1]
    
    print(is_palindrome("A man, a plan, a canal: Panama"))
    print(is_palindrome("race a car"))
  5. Climbing stairs: how many ways to climb N stairs if you can take 1 or 2 steps?
    ১ বা ২ ধাপে N সিঁড়ি উঠার কতগুলো উপায়?
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    def climb(n):
        a, b = 1, 1
        for _ in range(n):
            a, b = b, a + b
        return a
    
    print([climb(i) for i in range(10)])

Summary — Module 35

Most coding interviews are variations of five patterns: two pointers, sliding window, BFS/DFS, heap, and DP. Python's built-ins — heapq, bisect, collections.deque, Counter, @lru_cache — give you concise solutions. Clarify the problem, start with brute force, state complexity, and test with one example before you call it done.

বেশিরভাগ coding interview পাঁচটি pattern-এর variation: two pointers, sliding window, BFS/DFS, heap, DP। Python-এর built-in আপনাকে concise সমাধান দেয়। সমস্যা স্পষ্ট করুন, brute force থেকে শুরু করুন, complexity বলুন, এক example দিয়ে test করুন।

Next Module → Data Science Primer — NumPy, pandas, matplotlib।