Above template is excellent for building a structured, beginner-to-advanced problem-solving flow — and with a small enhancement, it can flexibly handle all types of problems, from simple to complex (e.g. Merge Sort, Backtracking, Dynamic Programming, etc.).
✅ Finalized Python Problem-Solving Template:
Let’s slightly enhance previous version to dynamically adapt to all problem types:
🧠 0. Understand the Problem (Add to every solution)
- Problem Statement: What exactly is asked?
- Input/Output format: Examples + edge cases
- Constraints: Time/space limits, input size
- Keywords: Sort, Search, Max/Min, Count, Path, Decision
✏️ 1. Write Pseudocode / Flow
- Step-by-step breakdown
- Conditions / Decisions
- Use diagrams if applicable (matrix, tree, array, etc.)
🧰 2. Choose Tools
- Which data structures? Why?
- Loop or Recursion?
- Sliding Window / DP / Stack / Queue?
🧪 3. Dry Run with Mini Input
- Manually run on 1–2 inputs
- Track variable changes
- Ensure logic holds
💻 4. Code
def get_input():
# Can be hardcoded, user, or file
return "abba"
def process(data):
# Core logic here
return data == data[::-1]
def show_output(result):
print("Is palindrome?", result)
def main():
data = get_input()
result = process(data)
show_output(result)
main()
✅ 5. Test & Debug
- Add
print()
at each logic step - Cover edge cases
🧠 Optional Enhancements:
- Add time/space complexity as docstring
- Write unit tests
- Make reusable function if needed
Now let’s include all previously discussed topics in this enhanced format using small data samples:
🧩 Example 1: Palindrome Check
🧠 Problem
Check if a string is a palindrome (same forwards and backwards).
Input: "abba"
→ Output: True
✏️ Pseudocode
- Compare start and end characters
- Move inward
- If mismatch → return False
🧰 Data Structure & Pattern
- Use string indexing and loop or slicing
💻 Code:
def get_input():
return "abba"
def process(s):
return s == s[::-1]
def show_output(result):
print("Palindrome?", result)
main()
🧩 Example 2: Merge Sort
🧠 Problem
Sort an array using the Divide & Conquer method.
Input: [4, 2, 1, 3]
Output: [1, 2, 3, 4]
✏️ Pseudocode
- Split array into halves
- Recursively sort each half
- Merge them in sorted order
🧰 Data Structure & Pattern
- Array + recursion
- Use merge technique with two pointers
💻 Code:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
L = merge_sort(arr[:mid])
R = merge_sort(arr[mid:])
return merge(L, R)
def merge(left, right):
i = j = 0
merged = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([4, 2, 1, 3]))
🧩 Example 3: Sliding Window – Max Sum Subarray of Size K
🧠 Problem
Find max sum of subarray of size K
Input: [1, 2, 3, 4, 5], K=2 → Output: 9
✏️ Pseudocode
- Create initial window of size K
- Slide forward: add next, remove prev
- Track max sum
💡 Pattern: Sliding Window
Efficient for continuous segments
💻 Code:
def max_sum_k(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k]
max_sum = max(max_sum, window_sum)
return max_sum
print(max_sum_k([1, 2, 3, 4, 5], 2))
🧩 Example 4: Binary Search
🧠 Problem
Find element x
in sorted array
Input: arr=[1, 2, 3, 4, 5], x=3 → Output: 2 (index)
✏️ Pseudocode
- Set
low=0, high=len(arr)-1
- Repeat:
- mid = (low + high) // 2
- If mid == x → return
- Else adjust low/high
💡 Pattern: Binary Search
Use when array is sorted
💻 Code:
def binary_search(arr, x):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 2, 3, 4, 5], 3))
Absolutely! Here’s a complete and interactive breakdown of 10 classic Python problems using your preferred template:
✅ Standard Problem-Solving Template
- Understand the Problem (Statement + Example)
- Write Pseudocode / Decision Tree / Flow
- Choose the Right Pattern + Data Structure
- Code using this structure:
def get_input(): ... def process(data): ... def show_result(result): ... def main(): ...
🔟 Core Problems with Template Breakdown
1. 🔙 Backtracking: Subsets Generation
Problem:
Given an array, return all possible subsets (the power set).
Example:
Input: [1,2]
→ Output: [[], [1], [2], [1,2]]
Pseudocode:
function backtrack(index, path):
add path to result
for i from index to len(nums):
call backtrack(i+1, path + [nums[i]])
Why Backtracking?
We need to explore all combinations (include/exclude).
Code:
def process(nums):
result = []
def backtrack(index, path):
result.append(path)
for i in range(index, len(nums)):
backtrack(i + 1, path + [nums[i]])
backtrack(0, [])
return result
def main():
print(process([1, 2]))
2. 🧠 DP: Fibonacci with Memoization
Problem:
Return nth Fibonacci number
Pseudocode:
If n in memo: return memo[n]
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
Why DP?
Avoid recomputation of overlapping subproblems.
Code:
def process(n):
memo = {}
def fib(n):
if n <= 1:
return n
if n in memo:
return memo[n]
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
return fib(n)
def main():
print(process(6)) # ➤ 8
3. 🔁 Recursion: Reverse a List
Problem:
Reverse a list using recursion
Pseudocode:
Base: if len(lst) <= 1: return lst
return reverse(rest) + [first]
Code:
def process(lst):
if len(lst) <= 1:
return lst
return process(lst[1:]) + [lst[0]]
def main():
print(process([1, 2, 3])) # ➤ [3,2,1]
4. 🔍 Matrix Traversal: DFS
Problem:
Check if a word exists in a grid using DFS
Example:
Search “ABCCED” in a char grid.
Pseudocode:
DFS from every cell
If match, mark visited and search 4 directions
Backtrack if not found
Code:
def process(board, word):
rows, cols = len(board), len(board[0])
path = set()
def dfs(r, c, i):
if i == len(word): return True
if (r < 0 or c < 0 or r >= rows or c >= cols or
word[i] != board[r][c] or (r, c) in path):
return False
path.add((r, c))
res = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or
dfs(r, c+1, i+1) or dfs(r, c-1, i+1))
path.remove((r, c))
return res
for r in range(rows):
for c in range(cols):
if dfs(r, c, 0): return True
return False
def main():
board = [["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]]
print(process(board, "ABCCED")) # ➤ True
5. 💡 Greedy: Interval Scheduling (Max Non-Overlapping)
Problem:
Given intervals, return max number of non-overlapping intervals.
Pseudocode:
Sort intervals by end
Track end; if current start >= end, count++
Code:
def process(intervals):
intervals.sort(key=lambda x: x[1])
count = 0
end = float('-inf')
for start, stop in intervals:
if start >= end:
count += 1
end = stop
return count
def main():
print(process([[1,3],[2,4],[3,5]])) # ➤ 2
6. 🧩 HashMap: Valid Anagram
Problem:
Check if two strings are anagrams.
Code:
def process(s, t):
if len(s) != len(t): return False
from collections import Counter
return Counter(s) == Counter(t)
def main():
print(process("listen", "silent")) # ➤ True
7. 📚 Stack: Valid Parentheses
Problem:
Check if input has valid brackets.
Pseudocode:
For each bracket:
If open, push to stack
If close, check top of stack
Code:
def process(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for ch in s:
if ch in mapping.values():
stack.append(ch)
elif ch in mapping:
if not stack or stack.pop() != mapping[ch]:
return False
return not stack
def main():
print(process("({[]})")) # ➤ True
8. 🚍 Queue: Sliding Window Max
Problem:
Return max in each sliding window of size k
Pseudocode (Using Deque):
Use deque to store index
Remove out-of-window + smaller elements
Code:
from collections import deque
def process(nums, k):
q, res = deque(), []
for i, n in enumerate(nums):
while q and q[0] <= i - k:
q.popleft()
while q and nums[q[-1]] < n:
q.pop()
q.append(i)
if i >= k - 1:
res.append(nums[q[0]])
return res
def main():
print(process([1,3,-1,-3,5,3,6,7], 3)) # ➤ [3,3,5,5,6,7]
9. ➗ Two Pointers: Sorted Pair Sum
Problem:
Find if two numbers sum to target in sorted array.
Code:
def process(arr, target):
l, r = 0, len(arr) - 1
while l < r:
s = arr[l] + arr[r]
if s == target:
return True
elif s < target:
l += 1
else:
r -= 1
return False
def main():
print(process([1,2,4,5,7,11], 9)) # ➤ True
10. 🌲 Trie: Prefix Matching
Problem:
Check if any word in list starts with given prefix.
Pseudocode:
Build Trie → For each char → traverse
Code:
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.end = True
def startsWith(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return True
def main():
t = Trie()
for word in ["apple", "app", "banana"]:
t.insert(word)
print(t.startsWith("ap")) # ➤ True
print(t.startsWith("ba")) # ➤ True
print(t.startsWith("gr")) # ➤ False
Leave a Reply