LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 18 of 19

Python Coding Interview Questions – Part 2 (Intermediate)

  • 7 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Learn the pattern, not the puzzle

Hash maps, stacks, sort-and-sweep, heaps, sliding windows and recursion solve most intermediate coding questions. Name the pattern before you code — interviewers notice.

  • HashingTwo sum, anagrams and frequency.
  • Stacks & windowsBrackets and unique substrings.
  • DesignIntervals, flattening and LRU cache.

These problems appear in online assessments and second-round interviews at product companies. Each one maps to a reusable pattern — hash maps, stacks, sorting, heaps, sliding windows — so learn the pattern, not just the answer.

1. Two Sum: return the indexes of two numbers that add up to a target.

Pattern: hash map of seen values. One pass, O(n) time and space, instead of the O(n²) double loop.

def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return seen[target - x], i
        seen[x] = i
    return None

print(two_sum([2, 7, 11, 15], 9))   # (0, 1)

2. Check whether brackets are balanced.

Pattern: stack. Push opening brackets; on a closing bracket, the top must be its partner. O(n).

def is_balanced(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

print(is_balanced("{[()()]}"), is_balanced("([)]"))   # True False

3. Group words that are anagrams.

Pattern: canonical key. Sorted letters (or a letter-count tuple) are the same for all anagrams.

from collections import defaultdict

def group_anagrams(words: list[str]) -> list[list[str]]:
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

4. Merge overlapping intervals.

Pattern: sort, then sweep. After sorting by start, an interval overlaps the last merged one if it starts before that one ends. O(n log n).

def merge(intervals: list[list[int]]) -> list[list[int]]:
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

print(merge([[1, 3], [8, 10], [2, 6], [15, 18]]))   # [[1, 6], [8, 10], [15, 18]]

5. Flatten a nested dictionary into dotted keys.

Pattern: recursion carrying a prefix. Common in config handling and JSON processing.

def flatten(d: dict, prefix: str = "") -> dict:
    flat = {}
    for key, value in d.items():
        name = f"{prefix}.{key}" if prefix else key
        if isinstance(value, dict):
            flat.update(flatten(value, name))
        else:
            flat[name] = value
    return flat

print(flatten({"db": {"host": "localhost", "port": 5432}, "debug": True}))
# {'db.host': 'localhost', 'db.port': 5432, 'debug': True}

6. Find the K most frequent elements.

Pattern: count + heap. Counter.most_common(k) is fine in practice; bucket sort gives O(n) if asked.

from collections import Counter
import heapq

def top_k(nums: list[int], k: int) -> list[int]:
    counts = Counter(nums)
    return heapq.nlargest(k, counts, key=counts.get)

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

7. Longest substring without repeating characters.

Pattern: sliding window. Track the last index of each character; when a repeat appears inside the window, move the left edge past it. O(n).

def longest_unique(s: str) -> int:
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

print(longest_unique("abcabcbb"))   # 3

8. Implement an LRU cache with O(1) operations.

Pattern: hash map + ordered structure. OrderedDict gives O(1) move-to-end and pop-oldest. Be ready to explain the hash map + doubly linked list design it hides.

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity, self.data = capacity, OrderedDict()

    def get(self, key):
        if key not in self.data:
            return -1
        self.data.move_to_end(key)          # mark as recently used
        return self.data[key]

    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)   # evict least recently used

Remember

Key points

  • “Seen before?” → hash map

    Turns O(n²) into O(n).

  • Matching pairs → stack

    Brackets, tags, undo.

  • Ranges → sort first

    Then a single sweep.

  • Contiguous → sliding window

    Substrings and subarrays.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Rotate a list by k positions. Basic

    k %= len(a); a[-k:] + a[:-k] — or collections.deque.rotate(k).

  2. 2 Find all pairs with a given sum in a sorted list. Intermediate

    Two pointers from both ends: move left up if the sum is small, right down if it is large — O(n).

  3. 3 Find the maximum subarray sum. Intermediate

    Kadane's algorithm, O(n).

    def max_subarray(nums):
        best = current = nums[0]
        for x in nums[1:]:
            current = max(x, current + x)
            best = max(best, current)
        return best
  4. 4 Check whether a string is a valid IPv4 address. Intermediate

    Split on dots, require four parts, each all digits, no leading zeros, value 0–255 — or use the ipaddress module in real code.

  5. 5 Find duplicates in a list in O(n). Basic

    [x for x, c in Counter(items).items() if c > 1].

  6. 6 Implement binary search. Basic

    Keep lo and hi, compare the middle, halve the range; or use the bisect module.

    def binary_search(a, target):
        lo, hi = 0, len(a) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if a[mid] == target:
                return mid
            if a[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
  7. 7 Find the first missing positive integer. Advanced

    With extra space: put values in a set and count up from 1. In O(1) space: place each value x at index x−1 by swapping, then scan for the first mismatch.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links