Top 25+ Python coding interview problems with solutions - arrays, strings, linked lists, sorting, searching, dynamic programming, and algorithmic challenges with Hindi explanations.
Introduction
Yeh guide top coding interview questions aur unke optimal Python solutions cover karta hai. Har solution ke saath time complexity, space complexity, aur explanation di gayi hai.
Q2: Palindrome Check
def is_palindrome_string(s):
"""
String palindrome hai ya nahi
'racecar' -> True
'hello' -> False
"""
# Two pointers approach
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
# One-liner
def is_palindrome_simple(s):
return s == s[::-1]
# Alphanumeric only palindrome (ignore spaces/punctuation)
def is_palindrome_alphanumeric(s):
"""
"A man, a plan, a canal: Panama" -> True
"""
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome_string("racecar")) # True
print(is_palindrome_string("hello")) # False
print(is_palindrome_simple("level")) # True
print(is_palindrome_alphanumeric("A man, a plan, a canal: Panama")) # True
# Integer palindrome
def is_palindrome_int(n):
if n < 0:
return False
s = str(n)
return s == s[::-1]
print(is_palindrome_int(121)) # True
print(is_palindrome_int(-121)) # False
print(is_palindrome_int(123)) # False
Q3: Fibonacci Sequence — Multiple Approaches
# Approach 1: Recursive (Exponential — very slow!)
def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
# Time: O(2^n), Space: O(n)
# Approach 2: Memoized recursion (fast)
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n <= 1:
return n
return fib_memo(n-1) + fib_memo(n-2)
# Time: O(n), Space: O(n)
# Approach 3: Dynamic Programming (iterative)
def fib_dp(n):
if n <= 1:
return n
prev, curr = 0, 1
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
# Time: O(n), Space: O(1) — BEST!
# Approach 4: Generator (infinite fibonacci)
def fib_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
import itertools
# First 10 fibonacci numbers
first_10 = list(itertools.islice(fib_generator(), 10))
print(first_10) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Test all approaches
for n in [0, 1, 5, 10, 20]:
print(f"fib({n}) = {fib_dp(n)}")
Q4: Anagram Check
from collections import Counter
def are_anagrams(s1, s2):
"""
'listen' aur 'silent' anagrams hain -> True
'hello' aur 'world' anagrams nahi -> False
"""
return Counter(s1) == Counter(s2)
# Alternative: sorted strings compare
def are_anagrams_sort(s1, s2):
return sorted(s1) == sorted(s2)
# Manual counter
def are_anagrams_manual(s1, s2):
if len(s1) != len(s2):
return False
count = {}
for c in s1:
count[c] = count.get(c, 0) + 1
for c in s2:
count[c] = count.get(c, 0) - 1
return all(v == 0 for v in count.values())
print(are_anagrams("listen", "silent")) # True
print(are_anagrams("hello", "world")) # False
print(are_anagrams("anagram", "nagaram")) # True
# Group anagrams
def group_anagrams(words):
"""['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] -> [['eat','tea','ate'],['tan','nat'],['bat']]"""
groups = {}
for word in words:
key = tuple(sorted(word)) # Sorted tuple as key
groups.setdefault(key, []).append(word)
return list(groups.values())
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
Q5: Binary Search
def binary_search(arr, target):
"""
Sorted array mein target find karo
O(log n) time, O(1) space
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2 # Overflow safe
if arr[mid] == target:
return mid # Found!
elif arr[mid] < target:
left = mid + 1 # Right half search
else:
right = mid - 1 # Left half search
return -1 # Not found
# Test
sorted_arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(binary_search(sorted_arr, 11)) # 5 (index)
print(binary_search(sorted_arr, 6)) # -1 (not found)
print(binary_search(sorted_arr, 1)) # 0 (first element)
print(binary_search(sorted_arr, 19)) # 9 (last element)
# Recursive version
def binary_search_recursive(arr, target, left=0, right=None):
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
print(binary_search_recursive(sorted_arr, 7)) # 3
# First and last occurrence
def find_first_last(arr, target):
def find_first(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # Continue searching left
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
def find_last(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
left = mid + 1 # Continue searching right
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
return find_first(arr, target), find_last(arr, target)
arr = [1, 2, 2, 2, 3, 4, 4, 5]
print(find_first_last(arr, 2)) # (1, 3)
print(find_first_last(arr, 4)) # (5, 6)
Q6: Reverse a String / Array
# String reverse
s = "Hello, World!"
print(s[::-1]) # !dlroW ,olleH
print(''.join(reversed(s))) # Same output
def reverse_words(sentence):
"""Words reverse karo, characters nahi"""
words = sentence.split()
return ' '.join(reversed(words))
print(reverse_words("Hello World Python")) # Python World Hello
# In-place array reverse (two pointers)
def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
print(reverse_array([1, 2, 3, 4, 5])) # [5, 4, 3, 2, 1]
# Rotate array by k positions
def rotate_array(nums, k):
n = len(nums)
k = k % n # Handle k > n
def reverse(left, right):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1; right -= 1
reverse(0, n-1) # Reverse all
reverse(0, k-1) # Reverse first k
reverse(k, n-1) # Reverse rest
return nums
print(rotate_array([1, 2, 3, 4, 5, 6, 7], 3)) # [5, 6, 7, 1, 2, 3, 4]
Q7: Find Duplicates in Array
def find_duplicates(nums):
"""
Array mein saare duplicate elements find karo
O(n) time, O(n) space
"""
seen = set()
duplicates = set()
for num in nums:
if num in seen:
duplicates.add(num)
seen.add(num)
return list(duplicates)
def find_duplicates_sort(nums):
"""Sorted approach — O(n log n) time, O(1) extra space"""
nums_copy = sorted(nums)
result = []
for i in range(1, len(nums_copy)):
if nums_copy[i] == nums_copy[i-1] and (not result or result[-1] != nums_copy[i]):
result.append(nums_copy[i])
return result
def first_duplicate(nums):
"""First duplicate element find karo"""
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
return None
print(find_duplicates([4, 3, 2, 7, 8, 2, 3, 1])) # [2, 3]
print(first_duplicate([2, 3, 4, 1, 3, 2])) # 3
from collections import Counter
def most_frequent(nums, k=3):
"""Top k frequent elements"""
count = Counter(nums)
return [num for num, freq in count.most_common(k)]
print(most_frequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]
Q8: Bubble Sort Implementation
def bubble_sort(arr):
"""
Time: O(n²), Space: O(1)
Small arrays ya nearly sorted ke liye
"""
n = len(arr)
arr = arr.copy() # Don't modify original
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped: # Already sorted!
break
return arr
def merge_sort(arr):
"""
Time: O(n log n), Space: O(n)
Stable sort — equal elements ka order preserve hota hai
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Quick Sort
def quick_sort(arr):
"""
Time: O(n log n) average, O(n²) worst
Space: O(log n) — in-place possible
"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Original: {arr}")
print(f"Bubble: {bubble_sort(arr)}")
print(f"Merge: {merge_sort(arr)}")
print(f"Quick: {quick_sort(arr)}")
# All: [11, 12, 22, 25, 34, 64, 90]
Q9: Linked List — Basic Operations
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
return f"Node({self.val})"
def list_to_linked(lst):
"""Python list to linked list"""
if not lst:
return None
head = ListNode(lst[0])
current = head
for val in lst[1:]:
current.next = ListNode(val)
current = current.next
return head
def linked_to_list(head):
"""Linked list to Python list"""
result = []
while head:
result.append(head.val)
head = head.next
return result
# Reverse Linked List
def reverse_linked_list(head):
"""O(n) time, O(1) space"""
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev # New head
# Find Middle of Linked List
def find_middle(head):
"""Slow-fast pointer technique"""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow # Middle element
# Detect Cycle (Floyd's Algorithm)
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
# Test
head = list_to_linked([1, 2, 3, 4, 5])
print(f"Original: {linked_to_list(head)}")
reversed_head = reverse_linked_list(head)
print(f"Reversed: {linked_to_list(reversed_head)}")
head2 = list_to_linked([1, 2, 3, 4, 5])
mid = find_middle(head2)
print(f"Middle: {mid.val}") # 3
Q10: Maximum Subarray Sum (Kadane's Algorithm)
def max_subarray_sum(nums):
"""
Kadane's Algorithm
Time: O(n), Space: O(1)
"""
max_sum = current_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
def max_subarray_with_indices(nums):
"""Maximum subarray sum aur uske indices bhi return karo"""
max_sum = current_sum = nums[0]
start = end = temp_start = 0
for i in range(1, len(nums)):
if nums[i] > current_sum + nums[i]:
current_sum = nums[i]
temp_start = i
else:
current_sum += nums[i]
if current_sum > max_sum:
max_sum = current_sum
start = temp_start
end = i
return max_sum, nums[start:end+1]
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(f"Max sum: {max_subarray_sum(nums)}") # 6
total, subarray = max_subarray_with_indices(nums)
print(f"Max sum {total}, subarray: {subarray}") # 6, [4, -1, 2, 1]
Q11: Valid Parentheses
def is_valid_parentheses(s):
"""
'()[]{}' -> True
'(]' -> False
'([)]' -> False
'{[]}' -> True
Stack approach — O(n) time, O(n) space
"""
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in '([{':
stack.append(char) # Opening bracket — push
elif char in ')]}':
if not stack or stack[-1] != mapping[char]:
return False # Mismatch!
stack.pop() # Match found — pop
return len(stack) == 0 # Stack empty means all matched
print(is_valid_parentheses("()[]{}")) # True
print(is_valid_parentheses("(]")) # False
print(is_valid_parentheses("{[]}")) # True
print(is_valid_parentheses("((")) # False — unclosed!
# Count minimum operations to make valid
def min_operations(s):
"""Minimum parentheses add/remove karne honge"""
open_count = 0
close_needed = 0
for char in s:
if char == '(':
open_count += 1
elif char == ')':
if open_count > 0:
open_count -= 1
else:
close_needed += 1
return open_count + close_needed
print(min_operations("())")) # 1
print(min_operations("(((")) # 3
Q12: Count Occurrences of Character
def count_char(s, char):
"""Character ki occurrences count karo"""
return s.count(char)
# Count all characters
from collections import Counter
def char_frequency(s):
"""String mein har character ki frequency"""
return dict(Counter(s))
# Most common character
def most_common_char(s):
counter = Counter(s)
return counter.most_common(1)[0]
s = "hello world python programming"
print(f"Count 'l': {count_char(s, 'l')}") # 4
print(f"Frequencies: {char_frequency('hello')}") # {'h':1,'e':1,'l':2,'o':1}
print(f"Most common: {most_common_char(s)}") # ('o', 5)
# First non-repeating character
def first_unique_char(s):
count = Counter(s)
for i, char in enumerate(s):
if count[char] == 1:
return i
return -1
print(first_unique_char("leetcode")) # 0 ('l')
print(first_unique_char("aabb")) # -1 (none)
Q13: FizzBuzz
def fizzbuzz(n):
"""Classic FizzBuzz problem"""
result = []
for i in range(1, n + 1):
if i % 15 == 0: # Divisible by both 3 and 5
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
print(fizzbuzz(20))
# Scalable FizzBuzz (extensible)
def fizzbuzz_scalable(n, rules=None):
"""Custom rules ke saath FizzBuzz"""
if rules is None:
rules = [(3, "Fizz"), (5, "Buzz")]
result = []
for i in range(1, n + 1):
output = "".join(word for divisor, word in rules if i % divisor == 0)
result.append(output or str(i))
return result
print(fizzbuzz_scalable(15))
print(fizzbuzz_scalable(15, [(3, "Fizz"), (5, "Buzz"), (7, "Bazz")]))
Q14: Find Missing Number
def find_missing(nums):
"""
[0, 1, 3] mein 2 missing hai
n numbers ka expected sum = n*(n+1)/2
Time: O(n), Space: O(1)
"""
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
print(find_missing([3, 0, 1])) # 2
print(find_missing([0, 1])) # 2
print(find_missing([9,6,4,2,3,5,7,0,1])) # 8
# XOR approach (handles 0)
def find_missing_xor(nums):
n = len(nums)
xor = n # XOR all expected numbers
for i, num in enumerate(nums):
xor ^= i ^ num
return xor
print(find_missing_xor([3, 0, 1])) # 2
Q15: String Compression
def compress_string(s):
"""
"aabcccdddd" -> "a2b1c3d4"
Agar compressed longer hai toh original return karo
"""
if not s:
return s
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(s[i-1])
result.append(str(count))
count = 1
result.append(s[-1])
result.append(str(count))
compressed = ''.join(result)
return compressed if len(compressed) < len(s) else s
print(compress_string("aabcccdddd")) # a2b1c3d4
print(compress_string("abcd")) # abcd (no compression benefit)
print(compress_string("aaaa")) # a4
# Run-length encoding
def rle_encode(s):
"""More detailed run-length encoding"""
if not s:
return []
encoded = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
encoded.append((s[i-1], count))
count = 1
encoded.append((s[-1], count))
return encoded
def rle_decode(encoded):
return ''.join(char * count for char, count in encoded)
enc = rle_encode("aaabbbccddddee")
print(enc) # [('a', 3), ('b', 3), ('c', 2), ('d', 4), ('e', 2)]
print(rle_decode(enc)) # aaabbbccddddee
Q16: Power of a Number (Fast Exponentiation)
def power(base, exp, mod=None):
"""
base^exp calculate karo
Fast exponentiation: O(log n) time
"""
if exp == 0:
return 1
if exp < 0:
base = 1 / base
exp = -exp
result = 1
current = base
while exp > 0:
if exp % 2 == 1: # Odd exponent
result *= current
if mod:
result %= mod
current *= current
if mod:
current %= mod
exp //= 2
return result
print(power(2, 10)) # 1024
print(power(3, 5)) # 243
print(power(2, -2)) # 0.25
print(power(2, 1000, mod=1000000007)) # Very large modular exponentiation
Q17: Flatten Nested List
def flatten(nested, depth=None):
"""
Nested list ko flat karo
[[1,2],[3,[4,5]]] -> [1,2,3,4,5]
"""
result = []
for item in nested:
if isinstance(item, list) and (depth is None or depth > 0):
next_depth = None if depth is None else depth - 1
result.extend(flatten(item, next_depth))
else:
result.append(item)
return result
print(flatten([1, [2, 3], [4, [5, 6]]])) # [1, 2, 3, 4, 5, 6]
print(flatten([1, [2, [3, [4, [5]]]]])) # [1, 2, 3, 4, 5]
print(flatten([1, [2, [3, [4]]]], depth=1)) # [1, 2, [3, [4]]]
# Using itertools.chain
from itertools import chain
def flatten_one_level(nested):
return list(chain.from_iterable(nested))
print(flatten_one_level([[1, 2], [3, 4], [5]])) # [1, 2, 3, 4, 5]
Q18: Count Vowels and Consonants
def count_vowels_consonants(s):
"""String mein vowels aur consonants count karo"""
s = s.lower()
vowels = set('aeiou')
vowel_count = sum(1 for c in s if c in vowels)
consonant_count = sum(1 for c in s if c.isalpha() and c not in vowels)
return vowel_count, consonant_count
s = "Hello World Python"
v, c = count_vowels_consonants(s)
print(f"Vowels: {v}, Consonants: {c}") # Vowels: 5, Consonants: 10
# Remove vowels from string
def remove_vowels(s):
return ''.join(c for c in s if c.lower() not in 'aeiou')
print(remove_vowels("Hello World")) # Hll Wrld
# Count words in string
def word_count(text):
words = text.strip().split()
count = {}
for word in words:
word = word.lower().strip('.,!?')
count[word] = count.get(word, 0) + 1
return count
text = "the quick brown fox jumps over the lazy dog the dog"
print(word_count(text))
Q19: Stack Implementation
class Stack:
"""Stack data structure — LIFO"""
def __init__(self):
self._data = []
def push(self, item):
self._data.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Stack is empty!")
return self._data.pop()
def peek(self):
if self.is_empty():
raise IndexError("Stack is empty!")
return self._data[-1]
def is_empty(self):
return len(self._data) == 0
def size(self):
return len(self._data)
def __repr__(self):
return f"Stack({self._data})"
# Stack use case: evaluate expression
def evaluate_postfix(expression):
"""Postfix expression evaluate karo"""
stack = Stack()
for token in expression.split():
if token.isdigit():
stack.push(int(token))
else:
b = stack.pop()
a = stack.pop()
if token == '+': stack.push(a + b)
elif token == '-': stack.push(a - b)
elif token == '*': stack.push(a * b)
elif token == '/': stack.push(int(a / b))
return stack.pop()
print(evaluate_postfix("2 3 + 4 *")) # 20 ((2+3)*4)
print(evaluate_postfix("5 1 2 + 4 * + 3 -")) # 14
# Stack usage
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(f"Peek: {s.peek()}") # 3
print(f"Pop: {s.pop()}") # 3
print(s) # Stack([1, 2])
Q20: Dynamic Programming — Coin Change
def coin_change(coins, amount):
"""
Minimum coins needed to make amount
coins = [1, 5, 10, 25], amount = 36 -> 3 (25+10+1)
Time: O(amount * len(coins)), Space: O(amount)
"""
# DP table
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # 0 amount ke liye 0 coins
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
dp[a] = min(dp[a], dp[a - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
print(coin_change([1, 5, 10, 25], 36)) # 3 (25+10+1)
print(coin_change([1, 2, 5], 11)) # 3 (5+5+1)
print(coin_change([2], 3)) # -1 (impossible)
# Knapsack problem (0/1)
def knapsack_01(weights, values, capacity):
"""
Maximum value given weight capacity
Time: O(n * capacity), Space: O(n * capacity)
"""
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
# Don't include item i
dp[i][w] = dp[i-1][w]
# Include item i (if it fits)
if weights[i-1] <= w:
dp[i][w] = max(dp[i][w], dp[i-1][w - weights[i-1]] + values[i-1])
return dp[n][capacity]
weights = [2, 3, 4, 5]
values = [3, 4, 5, 6]
capacity = 8
print(f"Max value: {knapsack_01(weights, values, capacity)}") # 10
Q21: Sliding Window — Maximum Sum Subarray of Size K
def max_sum_subarray_k(nums, k):
"""
Size k ka maximum sum subarray
Sliding Window: O(n) time, O(1) space
"""
if len(nums) < k:
return None
# First window
window_sum = sum(nums[:k])
max_sum = window_sum
# Slide window
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k] # Add new, remove old
max_sum = max(max_sum, window_sum)
return max_sum
print(max_sum_subarray_k([2, 1, 5, 1, 3, 2], 3)) # 9 (5+1+3)
print(max_sum_subarray_k([2, 3, 4, 1, 5], 2)) # 7 (3+4)
# Longest substring without repeating characters
def length_longest_unique(s):
"""Two-pointer sliding window"""
char_index = {}
max_len = start = 0
for end, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = end
max_len = max(max_len, end - start + 1)
return max_len
print(length_longest_unique("abcabcbb")) # 3 "abc"
print(length_longest_unique("bbbbb")) # 1 "b"
print(length_longest_unique("pwwkew")) # 3 "wke"
Q22: Matrix Operations
# Matrix transpose
def transpose(matrix):
"""rows aur columns swap karo"""
return [[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))]
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original:")
for row in m: print(row)
print("Transposed:")
for row in transpose(m): print(row)
# Rotate 90 degrees
def rotate_90(matrix):
"""Matrix ko 90 degrees clockwise rotate karo"""
n = len(matrix)
# Transpose then reverse each row
transposed = transpose(matrix)
return [row[::-1] for row in transposed]
print("Rotated 90°:")
for row in rotate_90(m): print(row)
# Search in sorted matrix
def search_matrix(matrix, target):
"""Start from top-right corner"""
row, col = 0, len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False
sorted_matrix = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
print(search_matrix(sorted_matrix, 5)) # True
print(search_matrix(sorted_matrix, 10)) # False
Time & Space Complexity Summary
| Algorithm | Time | Space |
|---|
| Linear search | O(n) | O(1) |
| Binary search | O(log n) | O(1) |
| Bubble sort | O(n²) | O(1) |
| Merge sort | O(n log n) | O(n) |
| Quick sort | O(n log n) avg | O(log n) |
| HashMap lookup | O(1) avg | O(n) |
| Two pointers | O(n) | O(1) |
| Sliding window | O(n) | O(1) |
| DP (coin change) | O(n*amount) | O(amount) |
Interview Tips: 1. Brute force se shuru karo, phir optimize karo 2. Time/Space complexity hamesha bolo 3. Edge cases discuss karo (empty array, single element) 4. Test cases manually trace karo 5. Python built-ins use karo — sorted(), Counter(), defaultdict()
📤 Expected Outputs — Code Examples
Q1: Two Sum Output
Q2: Palindrome Check Output
True
False
True
True
True
False
False
Q3: Fibonacci Sequence Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fib(0) = 0
fib(1) = 1
fib(5) = 5
fib(10) = 55
fib(20) = 6765
Q4: Anagram Check Output
True
False
True
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Q5: Binary Search Output
Q6: Reverse String / Array Output
!dlroW ,olleH
!dlroW ,olleH
Python World Hello
[5, 4, 3, 2, 1]
[5, 6, 7, 1, 2, 3, 4]
Q7: Find Duplicates Output
Q8: Sorting Algorithms Output
Original: [64, 34, 25, 12, 22, 11, 90]
Bubble: [11, 12, 22, 25, 34, 64, 90]
Merge: [11, 12, 22, 25, 34, 64, 90]
Quick: [11, 12, 22, 25, 34, 64, 90]
Q9: Linked List Output
Original: [1, 2, 3, 4, 5]
Reversed: [5, 4, 3, 2, 1]
Middle: 3
Q10: Kadane's Algorithm Output
Max sum: 6
Max sum 6, subarray: [4, -1, 2, 1]
Q11: Valid Parentheses Output
True
False
True
False
1
3
Q12: Count Occurrences Output
Count 'l': 3
Frequencies: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Most common: ('o', 4)
0
-1Q13: FizzBuzz Output
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']
Q14: Find Missing Number Output
Q15: String Compression Output
a2b1c3d4
abcd
a4
[('a', 3), ('b', 3), ('c', 2), ('d', 4), ('e', 2)]
aaabbbccddddeeQ16: Fast Exponentiation Output
Q17: Flatten Nested List Output
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]
[1, 2, [3, [4]]]
[1, 2, 3, 4, 5]
Q18: Count Vowels Output
Vowels: 5, Consonants: 10
Hll Wrld
{'the': 3, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 2}Q19: Stack Output
20
14
Peek: 3
Pop: 3
Stack([1, 2])
Q20: Dynamic Programming Output
Q21: Sliding Window Output
Q22: Matrix Output
Original:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Rotated 90°:
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
True
False
⚠️ Common Mistakes
Students coding interviews mein aksar yeh galtiyan karte hain — inhe avoid karo! 🚫
- Edge cases handle nahi karna — Empty array
[], single element [1], ya None input check karna bhool jaate hain. Interviewer yeh sabse pehle dekhta hai! 😤
- Brute force se seedha optimal likhne ki koshish — Pehle brute force bolo, phir optimize karo step-by-step. Interviewer ko thought process dikhana zaroori hai, direct optimal answer nahi chahiye 🧠
- Time/Space complexity nahi batana — Solution likh diya lekin O(n) ya O(n²) nahi bataya. Interviewer explicitly nahi poochega — tumhe khud bolna hai! ⏱️
- Global variables use karna — Functions mein global state use karna bahut bada red flag hai. Always pass parameters explicitly aur return values use karo 🔴
- Off-by-one errors —
range(n) vs range(n+1), left <= right vs left < right — yeh small mistakes infinite loops ya wrong answers de sakti hain. Dry run karo! 🐛
- Python-specific features ignore karna —
Counter(), defaultdict(), enumerate(), list comprehensions — yeh use nahi kiye toh interviewer ko lagega ki Python aata hi nahi 🐍
- Input ko modify kar dena without asking — Agar interviewer ne nahi bola ki "in-place karo" toh original array modify mat karo.
.copy() ya naya list banao pehle ✋
✅ Key Takeaways
- 🎯 Pattern recognition is key — 80% coding questions 5-6 patterns mein fit hote hain: Two Pointers, Sliding Window, HashMap, Binary Search, DFS/BFS, Dynamic Programming
- 🧠 Brute force → Optimize → Code — Yeh 3-step approach follow karo. Seedha optimal likhne ki zaroorat nahi, interviewer ko journey dikhao
- ⏱️ Time complexity samajhna mandatory hai — O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n). Har solution ke saath bolna zaroori hai
- 🐍 Python built-ins are your superpower —
Counter, heapq, bisect, itertools, collections.defaultdict — yeh sab use karna professional Python programmer ki pehchaan hai
- 📝 Dry run karo hamesha — Code likhne ke baad ek example pe manually trace karo. Isse bugs pakad mein aate hain aur interviewer ko confidence milta hai
- 🔄 Recursion vs Iteration samjho — Recursion readable hai lekin stack overflow ka risk hai. Bottom-up DP iteration se better hota hai production mein
- 💡 Edge cases pehle sochke bolo — Empty input, negative numbers, duplicates, very large input — yeh discuss karna maturity dikhata hai
- 🗣️ Communication > Code — Interview mein 60% marks communication ke hain. Chup-chaap code likhne se kaam nahi chalega — har step explain karo
- 📊 Space-Time tradeoff samjho — HashMap se O(n) space deke O(n) time milta hai vs O(1) space mein O(n²) time. Interviewer ko tradeoff batao
- 🏋️ Daily practice (minimum 2 problems) — Consistency beats cramming. Roz 2 questions solve karo LeetCode/HackerRank pe, 3 months mein expert ban jaoge
❓ FAQ
Q: Python coding interview ke liye kitne questions practice karne chahiye?
A: Minimum 100-150 questions practice karo covering all patterns. Quality > Quantity — ek pattern ke 10-15 questions solve karo aur pattern samjho rather than 500 random questions karke confuse hona 📊
Q: Kya Python slow hone ki wajah se interviews mein disadvantage hai?
A: Bilkul nahi! 🙅♂️ Python interviews mein sabse popular language hai kyunki code concise aur readable hota hai. Interviewer ko algorithm chahiye, language speed nahi. Plus, Python ke built-ins (Counter, heapq, bisect) itne powerful hain ki C++ se bhi jaldi code likh sakte ho!
Q: Interview mein agar solution nahi aaye toh kya karna chahiye?
A: Panic mat karo! 😌 Pehle brute force approach batao, phir hint maango politely. Apna thought process explain karte raho — "I'm thinking about using a HashMap here because..." Interviewer partially correct approach bhi evaluate karta hai. Silence sabse bura hai!
Q: DSA ke liye Python mein kaunsi libraries jaanni zaroori hain?
A: Yeh must-know hain: collections (Counter, defaultdict, deque), heapq (priority queue), bisect (binary search), itertools (combinations, permutations), functools (lru_cache for memoization). In 5 libraries se 90% interview problems cover ho jaate hain 🎯
Q: Online coding rounds mein time management kaise karein?
A: 3 questions hain aur 60 minutes milte hain typical round mein. Strategy: Easy (10 min) → Medium (20 min) → Hard (25 min), 5 min buffer. Agar ek problem mein stuck ho toh 5 min extra do max, phir next pe move karo. Partial solutions bhi marks dete hain! ⏰
Q: Kya system design bhi Python interviews mein poocha jaata hai?
A: Junior/mid-level pe mostly coding hi hota hai. Senior roles (5+ years) mein system design alag round hota hai. But coding round mein scalability mention karo — "This solution works for n up to 10^6" — yeh bonus impression deta hai 💪
Q: Recursion vs Iterative — interview mein kaunsa approach prefer karein?
A: Dono batao! 🎯 Pehle recursive solution do (easy to explain), phir iterative optimize karo. Interviewer ko dikhao ki tumhe pata hai recursion mein stack overflow ho sakta hai large inputs pe. DP problems mein top-down (recursion + memo) se start karo, phir bottom-up (iterative) bhi mention karo.
Q: LeetCode Easy solve ho rahi hain but Medium mein struggle ho raha hai — kya karein?
A: Yeh normal hai! 😅 Medium problems pattern-based hote hain. Ek pattern pe focus karo (e.g., Sliding Window) — 10-15 questions solve karo usi pattern ke. Template yaad karo. 2-3 weeks mein Medium comfortable ho jaayegi. Hard ke liye same strategy, but 4-6 weeks lagenge per pattern.
🎯 Interview Tips
Yeh pro tips follow karo Python coding interviews crack karne ke liye! 🚀
- "Think Aloud" approach rakho — Interviewer ko apna thought process sunao. "Main pehle brute force soch raha hoon jo O(n²) hoga, phir HashMap se O(n) kar sakta hoon" — yeh bolna code se zyada important hai! 🗣️
- Pehle clarifying questions poochho — Input kya type ka hai? Sorted hai? Duplicates hain? Negative numbers? Range kya hai? Yeh questions poochna mature developer ki pehchaan hai 🤔
- Examples pe dry run karo code likhne se pehle — Paper pe ya whiteboard pe 2-3 examples trace karo. Isse approach clear hoti hai aur bugs kam aate hain 📝
- Python idioms use karo —
for i, val in enumerate(arr) instead of for i in range(len(arr)). List comprehensions, f-strings, unpacking — yeh dikhata hai ki Python mein fluent ho 🐍
- Edge cases explicitly mention karo — Code likhne se pehle bolo: "Edge cases honge — empty array, single element, all duplicates, already sorted." Phir code mein handle karo. Interviewer impressed hota hai! ✅
- Space-Time tradeoff discuss karo — "HashMap use karke O(n) space deke time O(n²) se O(n) la sakta hoon. Kya extra space allowed hai?" — Yeh question poochna shows maturity 🧠
- Code clean aur readable likho — Meaningful variable names (
left, right, complement) use karo, i, j, x se bachho jab tak obvious na ho. Comments add karo critical lines pe 📖
- Test cases khud suggest karo — Code likhne ke baad bolo: "Let me test with normal case, edge case (empty), and large input." Phir manually trace karo. Self-testing bahut impressive lagta hai! 🧪
- Optimizations step-by-step batao — Brute force O(n²) → Sorting O(n log n) → HashMap O(n). Har step ka tradeoff explain karo. Yeh shows ki tumne problem deeply samjha hai 📈
- Confidence rakho, even if stuck — Agar 100% solution nahi aa raha toh partial approach batao, pseudocode likho, aur explain karo ki "given more time, I would optimize this using X." Never give up silently! 💪