Skip to content
Laviyx Learn

Try

DSA course menu

How to Solve Coding Interview Problems: A Step-by-Step Method

A repeatable method for coding interview problems: understand, work examples, brute force first, find the bottleneck, optimise with the right pattern, code, test and analyse complexity, plus a pattern-recognition table.

Intermediate7 min readUpdated
On this page

Interviewers care about how you reach a solution as much as whether you reach it. A calm, repeatable method beats trying to remember a solution you once saw. This lesson walks through one, using a real problem.

The method#

  1. Understand. Restate the problem in your own words. Ask about input size, value ranges, duplicates, negative numbers, empty input, and what to return if there is no answer.
  2. Work examples by hand. Make a small normal example and a few edge cases (empty, one item, all equal).
  3. Brute force first. Say the simplest correct solution and its complexity out loud, even if it is slow.
  4. Find the bottleneck. Which part repeats work? That is what to optimise.
  5. Optimise with a pattern. Most problems map to a known pattern (see the table below).
  6. Code it cleanly. Good names, small helper functions, no premature cleverness.
  7. Test. Trace your examples through the code, especially the edge cases.
  8. Analyse. State the final time and space complexity.

Worked example#

Given a list of numbers and a number k, return the length of the longest contiguous part whose sum is at most k. All numbers are positive.

Understand: contiguous means a slice nums[i:j]; positive numbers mean extending a slice always increases its sum. Examples: [1, 2, 3, 4, 5] with k = 7 gives 3 (1 + 2 + 3 = 6); an empty list gives 0.

Brute force: try every start and end. O(n²) slices, and summing each one makes it O(n³); keeping a running sum per start brings it to O(n²):

Python
def longest_at_most_brute(nums, k):
    best = 0
    for i in range(len(nums)):
        total = 0
        for j in range(i, len(nums)):
            total += nums[j]
            if total > k:
                break
            best = max(best, j - i + 1)
    return best

print(longest_at_most_brute([1, 2, 3, 4, 5], 7))
print(longest_at_most_brute([3, 1, 2, 1, 1], 4))
Output
3
3

Bottleneck: each new start throws away the sum it just computed. Pattern: a contiguous range plus positive numbers points to a sliding window: grow on the right, shrink on the left when the sum is too big.

Python
def longest_at_most(nums, k):
    left = total = best = 0
    for right, x in enumerate(nums):
        total += x
        while total > k:
            total -= nums[left]
            left += 1
        best = max(best, right - left + 1)
    return best

print(longest_at_most([1, 2, 3, 4, 5], 7))
print(longest_at_most([3, 1, 2, 1, 1], 4))
print(longest_at_most([], 5))
Output
3
3
0

Test against the brute force on many random inputs. This is the quickest way to catch bugs in an optimised solution, and it is worth doing in practice sessions:

Python
import random

def longest_at_most_brute(nums, k):
    best = 0
    for i in range(len(nums)):
        total = 0
        for j in range(i, len(nums)):
            total += nums[j]
            if total > k:
                break
            best = max(best, j - i + 1)
    return best

def longest_at_most(nums, k):
    left = total = best = 0
    for right, x in enumerate(nums):
        total += x
        while total > k:
            total -= nums[left]
            left += 1
        best = max(best, right - left + 1)
    return best

random.seed(42)
for _ in range(1000):
    nums = [random.randint(1, 9) for _ in range(random.randint(0, 12))]
    k = random.randint(0, 30)
    assert longest_at_most(nums, k) == longest_at_most_brute(nums, k), (nums, k)
print("1000 random tests passed")
Output
1000 random tests passed

Analyse: each index enters and leaves the window once, so O(n) time and O(1) space.

Recognising the pattern#

If the problem mentions…Try…
"have I seen this before?", pairs that sum to a target, countshash map or set
sorted input, pairs or triples, in-place changestwo pointers
contiguous subarray or substring, longest/shortest windowsliding window or prefix sums
sorted data, or "smallest value that works"binary search
next greater/smaller elementmonotonic stack
top k, k-th largest, merging sorted streamsheap
trees, nested structuresrecursion, tree traversals
shortest path, fewest steps, levelsBFS
connected regions, cycles, all pathsDFS, union-find
tasks with dependenciestopological sort
all combinations, permutations, arrangementsbacktracking
count ways, min/max cost, choices with overlapping subproblemsdynamic programming

Input size hints at the target complexity#

n up to aboutUsually acceptable
10–12O(n!) or O(2ⁿ · n): brute force, backtracking
20–25O(2ⁿ)
500O(n³)
5,000O(n²)
10⁵–10⁶O(n log n) or O(n)
largerO(log n) or O(1)

These are rough rules from typical time limits, not laws, but they tell you whether a brute force can be enough.

In the interview room#

  • Think aloud. Silence gives the interviewer nothing to help you with.
  • State assumptions and check them: "I'll assume the list fits in memory."
  • Start with something that works. A correct O(n²) solution beats an unfinished O(n) one.
  • Test before saying "done". Walk through your edge cases line by line.
  • Accept hints gracefully. Interviewers often guide you; using a hint well is a good signal.

Key takeaway#

Now practise: start with the Beginner Questions.

Finished this lesson?