LearnFrenzy
Sign in Take a free test

Python Programming · Topic 25 of 25

Python Coding Interview Questions Questions and Concepts

  • 5 exercises
  • 50 questions
  • ~75 min
  • Answers explained

Introduction & Syntax

Python Coding Interview Questions · Study material

Coding rounds at product companies, service companies and start-ups ask variations of the same few dozen problems: two sum, valid parentheses, longest substring without repeats, merge intervals, top k frequent, reverse a linked list, shortest path in a grid. What interviewers really test is whether you recognise the pattern behind a problem, choose the right data structure, state the time and space complexity, and write clean, correct code. This capstone topic shows the patterns in idiomatic Python and gives you 50 questions – including 20 complete coding problems with solutions, all run on Python 3.

On this page

  • Complexity of Python's lists, dicts, sets, deques and heaps
  • Hash map and two-pointer patterns
  • Sliding window
  • Stacks and heaps
  • BFS and binary search
  • Dynamic programming, and how to approach any problem

Know your data structures

Operationlistdict / setdequeheapq (list)
index / lookup by keyO(1) by indexO(1) averageO(n) in the middlemin at [0]: O(1)
x in containerO(n)O(1) averageO(n)O(n)
add at end / remove from endO(1)O(1)O(1)push / pop: O(log n)
add / remove at frontO(n)–O(1)–
sortO(n log n)––heapify: O(n)

Rule of thumb: membership tests in a loop → set; counting or lookups → dict (or Counter); queue → deque; "k largest/smallest" or a priority queue → heapq; sorted data → binary search with bisect.

Pattern 1: hash map

Trade memory for speed: store what you have seen in a dict or set so each new element is checked in O(1). Two sum, first unique character, anagram groups and duplicate detection all follow this pattern and turn O(n²) into O(n).

def two_sum(nums, target):
    """Indices of the two numbers that add up to target – O(n) with a dict."""
    seen = {}                                  # value -> index
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return []

def first_unique(s):
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    return next((i for i, ch in enumerate(s) if counts[ch] == 1), -1)

print(two_sum([2, 7, 11, 15], 9), two_sum([3, 3], 6))
print(first_unique("leetcode"), first_unique("aabb"))

Output

[0, 1] [0, 1]
0 -1

Pattern 2: two pointers

Two indices moving towards each other (or in the same direction) solve palindrome checks, pair sums in a sorted array, removing duplicates in place and merging sorted lists – in O(n) time and O(1) extra space.

def is_palindrome(s):
    s = [c.lower() for c in s if c.isalnum()]
    left, right = 0, len(s) - 1
    while left < right:                        # move inwards from both ends
        if s[left] != s[right]:
            return False
        left, right = left + 1, right - 1
    return True

def pair_with_sum(sorted_nums, target):        # needs SORTED input
    i, j = 0, len(sorted_nums) - 1
    while i < j:
        total = sorted_nums[i] + sorted_nums[j]
        if total == target:
            return sorted_nums[i], sorted_nums[j]
        if total < target:
            i += 1
        else:
            j -= 1
    return None

print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("race a car"))
print(pair_with_sum([1, 3, 4, 6, 8, 11], 10), pair_with_sum([1, 2, 3], 9))

Output

True False
(4, 6) None

Pattern 3: sliding window

For "best contiguous subarray or substring" problems, keep a window and update it incrementally as it slides – adding the new element and removing the old – instead of recomputing every window. Variable-size windows grow and shrink, often with a dict of last positions or counts.

def max_sum_window(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]        # slide: add the new item, drop the old one
        best = max(best, window)
    return best

def longest_unique_substring(s):
    last_seen = {}
    start = best = 0
    for i, ch in enumerate(s):
        if last_seen.get(ch, -1) >= start:     # repeat inside the window: move the start past it
            start = last_seen[ch] + 1
        last_seen[ch] = i
        best = max(best, i - start + 1)
    return best

print(max_sum_window([2, 1, 5, 1, 3, 2], 3))
print(longest_unique_substring("abcabcbb"), longest_unique_substring("pwwkew"), longest_unique_substring(""))

Output

9
3 3 0

Pattern 4: stacks and heaps

A list used as a stack (append / pop) matches brackets, evaluates expressions and finds the next greater element. heapq keeps a min-heap in a list: heappush and heappop are O(log n), nlargest / nsmallest give the top k, and pushing (priority, item) tuples builds a priority queue (negate numbers for a max-heap).

import heapq

def balanced(s):
    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([balanced(s) for s in ["([]{})", "(]", "((", "a(b)c"]])

nums = [7, 2, 9, 4, 1, 8]
print(heapq.nlargest(3, nums), heapq.nsmallest(2, nums))
heap = []
for task, priority in [("email", 3), ("bug", 1), ("docs", 5)]:
    heapq.heappush(heap, (priority, task))    # min-heap: smallest priority first
print([heapq.heappop(heap)[1] for _ in range(len(heap))])

Output

[True, False, False, True]
[9, 8, 7] [1, 2]
['bug', 'email', 'docs']

Pattern 5: BFS and binary search

Breadth-first search with a deque finds the shortest path in an unweighted grid or graph and traverses trees level by level. Binary search halves a sorted range each step – O(log n) – and bisect gives the position or insertion point directly.

from collections import deque
import bisect

def shortest_path(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    queue = deque([(start, 0)])
    seen = {start}
    while queue:
        (r, c), dist = queue.popleft()
        if (r, c) == goal:
            return dist
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "." and (nr, nc) not in seen:
                seen.add((nr, nc))
                queue.append(((nr, nc), dist + 1))
    return -1

grid = ["..#.",
        ".##.",
        "...."]
print(shortest_path(grid, (0, 0), (0, 3)))

scores = [35, 48, 52, 67, 71, 89]               # sorted
print(bisect.bisect_left(scores, 67), bisect.bisect_left(scores, 60))   # position / insertion point

Output

7
3 3

Pattern 6: dynamic programming

When a problem breaks into overlapping sub-problems (ways to climb stairs, minimum coins, longest increasing subsequence), compute each sub-result once – top-down with memoisation (@lru_cache) or bottom-up in a table or a few variables.

def climb_stairs(n):
    a, b = 1, 1                    # ways to reach step 0 and step 1
    for _ in range(n - 1):
        a, b = b, a + b            # ways(n) = ways(n-1) + ways(n-2)
    return b

def max_subarray(nums):            # Kadane: best sum ending here vs overall best
    best = current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best

print([climb_stairs(n) for n in range(1, 8)])
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]), max_subarray([-3, -1, -2]))

Output

[1, 2, 3, 5, 8, 13, 21]
6 -1

How to approach a coding question

  1. Understand: restate the problem, ask about input size, duplicates, negatives, empty input.
  2. Examples: work through a small example and the edge cases by hand.
  3. Brute force first: say it and its complexity, then look for a pattern that improves it.
  4. Plan: choose the data structure; explain the idea before coding.
  5. Code: clean names, small helper functions, no premature tricks.
  6. Test and analyse: run your examples and edge cases; state time and space complexity.

Key points to remember

  • dict/set lookups are O(1); list membership is O(n).
  • Use deque for queues, heapq for priority and top-k problems.
  • Two pointers need sorted input (or a palindrome-style symmetry).
  • Sliding windows update incrementally instead of recomputing.
  • BFS finds shortest paths in unweighted graphs.
  • Binary search and bisect need sorted data.
  • Always state complexity and test edge cases: empty, one element, duplicates, negatives.

Frequently asked questions

Is Python a good language for coding interviews?

Yes – its concise syntax and rich built-ins (dict, set, deque, heapq, Counter, bisect, lru_cache) let you focus on the algorithm. Do mention complexity, because built-ins hide costs (e.g. list.pop(0) is O(n)).

Can I use library functions such as sorted() or Counter?

Usually yes, but be ready to explain how they work and their complexity, or to implement the core idea yourself if asked.

What should I practise first?

Arrays and strings with hash maps, two pointers and sliding windows; then stacks, queues, heaps; then trees, graphs (BFS/DFS) and dynamic programming.

Where can I learn more?

Revise Python Functions and Choosing the Right Collection in the Python tutorial, then solve the coding problems below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links