Absolutely! Here’s a structured, consistent Python problem-solving framework with 15+ real examples demonstrating:


✅ Standard Problem-Solving Template: Write → Visualize → Then Code

Template Structure

# 1. Input: Get the input (CLI, file, API, etc.)
def get_input():
    return input("Enter value: ")

# 2. Process: Core logic (heart of problem)
def process(data):
    # Logic using patterns (loop, stack, counter, etc.)
    return result

# 3. Output: Show or return the result
def show_result(result):
    print("Result:", result)

# 4. Main entry
def main():
    data = get_input()
    result = process(data)
    show_result(result)

main()

✅ Decision Making Guide: When to Use What

Problem TypePattern / DS to UseTip
String manipulationLoop, slicing, two-pointerFor reverse/palindrome
CountingDict / collections.CounterUse .get(k, 0) pattern
Matching conditionsIf-else, boolean flagsKeep flow diagrams
Frequency / groupingHashmap, defaultdictPre-count, then apply logic
Sorting / Searchingsorted(), binary searchUse bisect if large data
Min/Max Distance / DifferenceGreedy, sliding windowOptimize using pointers
Brute-force vs EfficientNested loops → optimized loop/DSStart brute, then optimize
Subarray/SubsequencePrefix sum, sliding window, DPVisualize ranges carefully

✅ 15+ Python Examples (With This Format)


1. Palindrome Check

Problem:

Check if input string is palindrome.

def get_input():
    return input("Enter string: ")

def process(data):
    return data == data[::-1]

def show_result(result):
    print("Palindrome?" , result)

main()

2. Check Anagram (string reordering match)

from collections import Counter

def process(data):
    str1, str2 = data
    return Counter(str1) == Counter(str2)

def main():
    str1 = input("First string: ")
    str2 = input("Second string: ")
    result = process((str1, str2))
    show_result(result)

3. Find First Non-Repeating Character

from collections import Counter

def process(data):
    count = Counter(data)
    for ch in data:
        if count[ch] == 1:
            return ch
    return None

4. Binary Search in Sorted Array

def process(data):
    nums, target = data
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

5. Reverse Words in Sentence

def process(data):
    return ' '.join(data.split()[::-1])

6. Count Vowels in a String

def process(data):
    return sum(1 for ch in data if ch in "aeiouAEIOU")

7. Check Balanced Parentheses

def process(data):
    stack = []
    match = {')':'(', ']':'[', '}':'{'}
    for ch in data:
        if ch in match.values():
            stack.append(ch)
        elif ch in match:
            if not stack or stack.pop() != match[ch]:
                return False
    return not stack

8. Fibonacci Using Memoization (DP)

def process(n, memo = {}):
    if n <= 1:
        return n
    if n not in memo:
        memo[n] = process(n-1, memo) + process(n-2, memo)
    return memo[n]

9. Find Duplicates

def process(data):
    seen = set()
    for val in data:
        if val in seen:
            return val
        seen.add(val)
    return None

10. Sort by Frequency

from collections import Counter

def process(data):
    count = Counter(data)
    return sorted(data, key=lambda x: (-count[x], x))

11. Minimum Distance Between Equal Elements

def process(data):
    last_index = {}
    min_dist = float('inf')
    for i, val in enumerate(data):
        if val in last_index:
            min_dist = min(min_dist, i - last_index[val])
        last_index[val] = i
    return min_dist if min_dist != float('inf') else -1

12. Sliding Window Max Sum

def process(data):
    arr, k = data
    max_sum = current = sum(arr[:k])
    for i in range(k, len(arr)):
        current += arr[i] - arr[i - k]
        max_sum = max(max_sum, current)
    return max_sum

13. Remove Duplicates from Sorted Array

def process(data):
    if not data: return []
    result = [data[0]]
    for num in data[1:]:
        if num != result[-1]:
            result.append(num)
    return result

14. Find Missing Number (0 to n)

def process(data):
    n = len(data)
    expected = n * (n + 1) // 2
    return expected - sum(data)

15. Majority Element (Boyer–Moore Voting Algorithm)

def process(data):
    count = 0
    candidate = None
    for num in data:
        if count == 0:
            candidate = num
        count += (1 if num == candidate else -1)
    return candidate

16. Merge Intervals

def process(data):
    data.sort()
    merged = [data[0]]
    for start, end in data[1:]:
        last_end = merged[-1][1]
        if start <= last_end:
            merged[-1][1] = max(last_end, end)
        else:
            merged.append([start, end])
    return merged

🧠 Visual Strategy

  • For each problem:
    • Draw input → logic flow
    • Identify pattern (e.g., loop + set, hashmap, recursion)
    • Think in steps, not syntax
    • Then write the code

🔁 Summary

StepDescription
WritePen-down pseudo-code first or dry-run with print
VisualizeTree, flowchart, or example walkthrough
Then CodeInput → Process → Output structure
Pattern FirstMatch with logic style: loop, counter, window, recursion
Optimize LaterFirst solve, then improve

Pages: 1 2

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *