Back to Blog

Coding Interview Patterns Cheat Sheet with Python Code

Six reusable coding interview patterns with short Python code, expected output and clues for spotting each one. Built for Indian students preparing for campus and off-campus rounds.

Hello Engineers
Hello Engineers
1 December 202610 min read62 views
Coding Interview Patterns Cheat Sheet with Python Code

Coding interview patterns are reusable approaches that solve many different questions. Learn six of them: two pointers, sliding window, hash map, binary search, prefix sum and stack. Then match each new question to a pattern instead of guessing. This cheat sheet gives Python code, expected output and clues for each pattern.

HelloEngineers is a community for engineering students in India. Many of us start interview prep by solving random questions. That feels busy, but it rarely sticks. Patterns fix that.

Key takeaways

  • A pattern is a way of thinking. One pattern solves dozens of questions.
  • Learn to spot the clue in the question first, then pick the pattern.
  • Start with six patterns: two pointers, sliding window, hash map, binary search, prefix sum, stack.
  • Always say the brute-force idea first, then improve it. Interviewers like this.
  • Practise 5 to 8 questions per pattern, not 100 random ones.
  • All code below targets Python 3.8 or later.

Why should you learn coding interview patterns instead of solving random questions?

Campus and off-campus coding rounds usually have a time limit. You may have 30 to 45 minutes per question. You cannot invent a new method from scratch under that pressure.

Patterns give you a starting point. You read the question, notice a clue, and recall a method you have already practised. Your brain does less work, and you make fewer silly mistakes.

This also helps if you are weak at DSA right now. If you need the basics first, follow the DSA roadmap for beginners and come back here.

Which pattern should you use? A quick clue table

Save this table. It is the fastest way to decide.

Clue in the questionPattern to tryTypical speed
Sorted array, find a pairTwo pointersO(n)
Longest or best subarray or substring of size kSliding windowO(n)
"Have I seen this before?", count, find duplicatesHash mapO(n)
Sorted data, or answer lies in a rangeBinary searchO(log n)
Many range-sum queriesPrefix sumO(n) build, O(1) query
Brackets, undo, nearest greater elementStackO(n)

O(n) means time grows in a straight line with input size. O(log n) means the work halves at every step.

How does the two pointers pattern work?

Use two indexes that move towards each other, or in the same direction. It works best on sorted data. It replaces a nested loop (O(n²)) with one pass (O(n)).

Example: find a pair with a given sum in a sorted array

python
def pair_with_sum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (left, right)
        if total < target:
            left += 1      # need a bigger sum
        else:
            right -= 1     # need a smaller sum
    return None

print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))

Expected output:

(2, 3)

The numbers at index 2 and 3 are 4 and 6, and 4 + 6 = 10. Because the array is sorted, moving the left pointer raises the sum and moving the right pointer lowers it.

How does the sliding window pattern work?

Keep a window of elements and slide it one step at a time. Do not recompute everything. Add the new element and remove the old one.

Example: maximum sum of any k consecutive elements

python
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]   # add new, remove old
        best = max(best, window)
    return best
SponsoredHelloEngineersJoin Now

print(max_sum_window([2, 1, 5, 1, 3, 2], 3))

Expected output:

9

The windows are [2,1,5]=8, [1,5,1]=7, [5,1,3]=9 and [1,3,2]=6. The best is 9. The clue words are "subarray", "substring" or "k consecutive". ## How does the hash map pattern help in interviews? A hash map (a Python dict) lets you look up a value in O(1) on average. Use it when you need to remember what you have already seen. ### Example: Two Sum on an unsorted array ```python def two_sum(nums, target): seen = {} # value -> index for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return [] print(two_sum([2, 7, 11, 15], 9))

Expected output:

[0, 1]

Brute force checks every pair, which is O(n²). The hash map checks each number once. Say both versions out loud in an interview.

When should you use binary search?

Use binary search when the data is sorted, or when the answer lies in a range and you can test whether a guess is too high or too low. Each step throws away half the options.

Example: find a target in a sorted array

python
def binary_search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11], 7))
print(binary_search([1, 3, 5, 7, 9, 11], 4))

Expected output:

3 -1

The loop condition lo <= hi and the mid + 1 / mid - 1 updates are where most bugs happen. Trace a tiny example on paper before you submit.

How does the prefix sum pattern work?

Build a running total once. Then any range sum is one subtraction. Use it when the question asks for many range-sum queries.

Example: sum of elements between two indexes

python
def build_prefix(nums):
    prefix = [0]
    for x in nums:
        prefix.append(prefix[-1] + x)
    return prefix

def range_sum(prefix, i, j):          # inclusive i..j
    return prefix[j + 1] - prefix[i]

nums = [3, 1, 4, 1, 5]
p = build_prefix(nums)
print(p)
print(range_sum(p, 1, 3))

Expected output:

[0, 3, 4, 8, 9, 14] 6

The elements at index 1 to 3 are 1, 4 and 1, which add up to 6. The extra leading 0 in the prefix list avoids special cases at index 0.

How does the stack pattern work?

A stack is last-in, first-out. Use it when the most recent item matters most: brackets, undo steps, or the nearest bigger element.

Example: valid parentheses

python
def is_valid(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

print(is_valid("({[]})"))
print(is_valid("(]"))

Expected output:

True False

An opening bracket goes on the stack. A closing bracket must match the top. At the end the stack must be empty.

What is a simple 2-week plan to practise these patterns?

Keep it small. Consistency beats long weekend marathons, especially during semester exams.

  1. Days 1–2: Two pointers. Re-type the code above from memory, then solve 4 similar questions.
  2. Days 3–4: Sliding window. Same routine.
  3. Days 5–6: Hash map. Practise counting and duplicate-finding questions.
  4. Days 7–8: Binary search. Trace by hand before coding.
  5. Days 9–10: Prefix sum and stack.
  6. Days 11–14: Mixed set. Do not tell yourself the pattern. Spot the clue first, then solve with a timer.

When you finish, test yourself on the top 100 coding interview questions with solutions. If Python syntax slows you down, revisit the Python roadmap for beginners.

SponsoredHello_EngineersLearn More

Some patterns, such as backtracking and tree problems, build on recursion. Read recursion explained with real examples before you move on to them.

How should you explain your answer in the interview?

Code is only half the round. Use this order every time:

  1. Repeat the question in your own words and ask about edge cases (empty input, duplicates, negative numbers).
  2. Say the brute-force idea and its time cost.
  3. Name the pattern and why the clue fits.
  4. Write the code in small, clear steps.
  5. Test with a small example out loud.
  6. State time and space complexity.

If you also have Java rounds, see the top 50 Java interview questions with answers. The patterns are the same in any language.

Common mistakes

  • Memorising solutions. You forget them under pressure. Memorise the clue and the idea instead.
  • Jumping to code. Spend the first 3 to 5 minutes on examples and edge cases.
  • Using two pointers on unsorted data. The pattern needs sorted order. Sort first, or use a hash map.
  • Off-by-one errors in binary search. Always test a one-element and a two-element array.
  • Ignoring complexity. A correct O(n²) answer may still fail the time limit on an online test.
  • Not practising without autocomplete. Many college tests use basic editors.

Best practices

  • Keep a notebook with one page per pattern: clue, template code, one mistake you made.
  • Re-solve a question after 3 days without looking at the solution.
  • Time yourself from week 2 onwards.
  • Pick one language and stay with it until the patterns feel natural.
  • Talk through your approach even when practising alone.

FAQ

How many coding interview patterns do I need to know?

Start with six: two pointers, sliding window, hash map, binary search, prefix sum and stack. They cover a large share of beginner and fresher-level questions. Later add recursion, trees, graphs and dynamic programming. Depth in a few patterns beats shallow knowledge of many.

Is Python good enough for coding interviews in India?

Yes, for most online assessments and coding rounds Python is accepted, and its short syntax saves time. Check the allowed languages in each test, since some companies restrict them. Also, some interviewers may ask follow-up questions on Java or C++ basics, so know one more language lightly.

How long does it take to learn these patterns?

With about one hour a day, the two-week plan above gives you a first pass over all six. Real comfort takes longer and varies per student. Keep solving mixed questions every week, and do not judge yourself by speed in the first month.

Should I solve questions by topic or by pattern?

Begin with patterns, because they teach you how to recognise a problem. Later, mix topics so you practise spotting the pattern yourself. Real interviews never tell you which pattern to use, so mixed practice is the final step.

What if I cannot solve a question in the interview?

Do not go silent. Explain the brute-force method, point out why it is slow, and try the pattern you think fits. Interviewers often give hints and judge your thinking. A clear partial solution is better than a blank screen.

Next step on HelloEngineers

Pick one pattern today, solve three questions, and share what you learned in the HelloEngineers discussions. You can also check jobs and internships to see which skills they ask for. Remember, genuine companies never charge a fee for jobs or internships.

Did you find this helpful?

Hello Engineers
Hello Engineers

I m the founder member of Helloengineers

34 articles7 followers
View Profile

Comments (0)

Sign in to leave a comment

Related Articles

Join HelloEngineers

Connect with engineering students across India. Share your knowledge, build your reputation.

SponsoredHello EngineersJoin Now
SponsoredHello_EngineersJoin Now
SponsoredHello_EngineersJoin Now