Algorithmic Problem Solving in Python (LeetCode)
অ্যালগরিদম — Python-এ LeetCode / কোডিং ইন্টারভিউ কৌশল
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.
2. Pattern 1 — Two Pointers
Use two indices moving through an array — often reducing O(n²) brute force to O(n).
# 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
# 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
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)
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
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 (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Brute force | The simplest, usually slowest solution. | সবচেয়ে সহজ, সাধারণত ধীর সমাধান। |
| Two pointers | Two indices scanning an array. | Array-এ একসাথে দুটি index চলে। |
| Sliding window | A moving subarray/range. | চলমান subarray/range। |
| Memoization | Caching results (lru_cache). | ফলাফল cache করা। |
| Priority queue | Queue ordered by priority (heapq). | Priority-ভিত্তিক queue। |
9. Practice Problems
-
Two Sum (unsorted): return indices of two numbers that add up to target.Unsorted array থেকে দুটি সংখ্যার index বের করুন যাদের যোগফল target।
✨ Show Answer (উত্তর দেখুন)
ans1.pydef 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)) -
Reverse a linked list (simulate with a list of nodes).Linked list reverse করুন।
✨ Show Answer (উত্তর দেখুন)
ans2.pyclass 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))) -
Find the k-th largest element in a list using
heapq.heapqদিয়ে k-তম বৃহত্তম সংখ্যা বের করুন।✨ Show Answer (উত্তর দেখুন)
ans3.pyimport heapq def kth_largest(nums, k): return heapq.nlargest(k, nums)[-1] print(kth_largest([3, 1, 4, 1, 5, 9, 2, 6], 3)) -
Given a string, check if it's a valid palindrome ignoring non-alphanumeric and case.Non-alphanumeric ও case ignore করে palindrome check করুন।
✨ Show Answer (উত্তর দেখুন)
ans4.pydef 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")) -
Climbing stairs: how many ways to climb N stairs if you can take 1 or 2 steps?১ বা ২ ধাপে N সিঁড়ি উঠার কতগুলো উপায়?
✨ Show Answer (উত্তর দেখুন)
ans5.pydef 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.