🐍
Syllabus / Python Programming / Phase 6: Mini Projects, Coding Challenges, Interview Preparation (Days 26–30)
Intermediate

Coding Challenges: List and Dictionary Problems

📂 Phase 6: Mini Projects, Coding Challenges, Interview Preparation (Days 26–30) · Python Programming

List and dictionary problems form the backbone of fresher and junior-level coding rounds — testing whether you can manipulate collections efficiently, recognize when a dictionary or set will outperform a naive nested loop, and reason clearly about time complexity.

Challenge 1: Find the Second-Largest Number in a List

def second_largest(numbers):
    unique_sorted = sorted(set(numbers), reverse=True)
    if len(unique_sorted) < 2:
        return None
    return unique_sorted[1]

print(second_largest([10, 5, 20, 8, 20]))   # 10 — duplicates of the largest are ignored
Using set() first removes duplicate values before sorting — without it, a list like [20, 20, 10] would incorrectly return 20 again as the "second largest" instead of 10.

Challenge 2: Remove Duplicates From a List While Preserving Order

def remove_duplicates(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

print(remove_duplicates([1, 2, 2, 3, 1, 4]))   # [1, 2, 3, 4]

Simply converting to set(items) would also remove duplicates, but sets are unordered — this approach preserves the original order, which interviewers frequently require explicitly.

Challenge 3: Find the Intersection of Two Lists

def find_intersection(list1, list2):
    return list(set(list1) & set(list2))

print(find_intersection([1, 2, 3, 4], [3, 4, 5, 6]))   # [3, 4] (order may vary)

Challenge 4: Word Frequency Counter From a Sentence

from collections import Counter

def word_frequency(sentence):
    words = sentence.lower().split()
    return Counter(words)

text = "the quick brown fox jumps over the lazy fox"
print(word_frequency(text))
# Counter({'the': 2, 'fox': 2, 'quick': 1, 'brown': 1, 'jumps': 1, 'over': 1, 'lazy': 1})

Challenge 5: Group Items by a Property (Dictionary of Lists)

students = [
    {"name": "Vishwas", "grade": "A"},
    {"name": "Priya", "grade": "B"},
    {"name": "Arjun", "grade": "A"},
]

grouped = {}
for student in students:
    grade = student["grade"]
    grouped.setdefault(grade, []).append(student["name"])

print(grouped)
# {'A': ['Vishwas', 'Arjun'], 'B': ['Priya']}

.setdefault(key, []) returns the existing list for that key if present, or creates a new empty list automatically if the key doesn't exist yet — avoiding a manual "if key not in dict" check.

Challenge 6: Find Two Numbers That Sum to a Target (Two Sum)

def two_sum(numbers, target):
    seen = {}
    for index, num in enumerate(numbers):
        complement = target - num
        if complement in seen:
            return [seen[complement], index]
        seen[num] = index
    return None

print(two_sum([2, 7, 11, 15], 9))   # [0, 1] — numbers[0] + numbers[1] = 2 + 7 = 9
This is one of the most famous coding interview problems across every language. The naive approach checks every pair with nested loops (O(n²)); the dictionary-based approach above does it in a single pass (O(n)) by remembering what value would complete each number as it goes.

Challenge 7: Flatten a Nested List

def flatten(nested_list):
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten(item))   # recursive call for nested lists
        else:
            result.append(item)
    return result

print(flatten([1, [2, 3], [4, [5, 6]]]))   # [1, 2, 3, 4, 5, 6]

Time Complexity Cheat Sheet

ProblemNaive ApproachOptimized Approach
Two SumO(n²) — nested loopO(n) — dictionary lookup
Find duplicatesO(n²) — compare every pairO(n) — set membership check
List intersectionO(n×m) — nested loopO(n+m) — set intersection
Interview tip: Whenever a problem involves checking "have I seen this before?" or "what pairs/combinations exist?", a dictionary or set is almost always the key to turning an O(n²) brute-force solution into an O(n) one — recognizing this pattern quickly is one of the strongest signals of fluency interviewers look for.