Skip to content
article

Read the constraints first: how I pick the pattern in under 2 minutes

A cheat sheet from six years of mock interviews. Constraints, keywords, and a template for each pattern, including the sliding window everybody gets wrong.

Nikhil Sharan@nikhil_twopointers

September 9, 2026 · 5 min read

Most people read the story in a problem and skip the constraints. The story is decoration. The constraints tell you the complexity you are allowed, and the complexity tells you the pattern. This is the routine I use, and the one I have been teaching in mocks for six years.

Step 1: constraints → your budget

Rough rule: a judge does about 10^8 simple operations per second in C++ or Java. So:

  • n ≤ 20: exponential is fine. Backtracking, bitmasks. O(2^n · n).
  • n ≤ 500: O(n³) works. Interval DP, Floyd-Warshall.
  • n ≤ 5,000: O(n²) works. Most 2D DP.
  • n ≤ 2 × 10^5: you need O(n log n) or O(n). Sorting, two pointers, sliding window, heaps, binary search, monotonic stack.
  • n ≤ 10^7 or more: O(n) with a small constant, or maths.
  • Values up to 10^9 and the question says "minimum possible" or "maximum possible": binary search on the answer, very likely.

Edit, after a fair correction in the comments: in Python, think 10 to 50 times fewer operations per second. n log n at 2 × 10^5 is fine, but n² at 5,000 can already be tight.

Write the budget at the top of your page before anything else: "n = 10^5 → n log n". It changes how you think for the next 40 minutes.

Step 2: keywords → pattern

  • "sorted", "pair", "triplet" → two pointers
  • "contiguous subarray / substring" + "longest / shortest / at most / at least" → sliding window
  • "next greater / next smaller", "span", "histogram" → monotonic stack
  • "minimize the maximum", "finish within D days" → binary search on the answer
  • "k largest", "k closest", "running median" → heap
  • "number of ways", "minimum cost to reach" with choices at every step → DP
  • shortest path in a grid, every move costs the same → BFS. Different non-negative costs → Dijkstra
  • "order", "prerequisites", "dependencies" → topological sort
  • "groups", "connected", merging things as you go → DSU (union find)
  • "subarray sum equals k" and the array can have negatives → prefix sum + hashmap
  • range sums with updates in between → Fenwick tree / segment tree (added after a comment, rare in SDE-1 interviews, common in some OAs)

Step 3: the sliding window template

This is the one people get wrong most, so here is the full template. Problem: the longest substring with at most k distinct characters.

int longestAtMostK(String s, int k) {
    int[] freq = new int[128];
    int distinct = 0, best = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        if (freq[s.charAt(right)]++ == 0) distinct++;      // grow the window
        while (distinct > k) {                             // shrink until valid again
            if (--freq[s.charAt(left)] == 0) distinct--;
            left++;
        }
        best = Math.max(best, right - left + 1);            // window is valid here
    }
    return best;
}

Dry run, s = "eceba", k = 2:

  • right=0 'e': distinct 1, best 1
  • right=1 'c': distinct 2, best 2
  • right=2 'e': distinct 2, best 3 ("ece")
  • right=3 'b': distinct 3, too many. Drop 'e' (still one 'e' left), left=1. Drop 'c', distinct 2, left=2. Window "eb".
  • right=4 'a': distinct 3. Drop 'e', distinct 2, left=3. Window "ba".

Answer 3. The reason it is O(n): left only ever moves forward, so each character enters once and leaves once.

Two things that make this template powerful:

  • "Exactly k" questions: exactly(k) = atMost(k) - atMost(k - 1). Write atMost once, call it twice. Many people never see this trick and struggle for an hour.
  • Why it breaks with negative numbers: the window logic assumes that removing an element from the left makes the sum smaller. With negatives, removing -3 makes the sum bigger. So for "subarray sum equals k" with negatives, use prefix sums instead:
int subarraySum(int[] a, int k) {
    Map<Integer, Integer> seen = new HashMap<>();
    seen.put(0, 1);                       // empty prefix
    int sum = 0, count = 0;
    for (int x : a) {
        sum += x;
        count += seen.getOrDefault(sum - k, 0);
        seen.merge(sum, 1, Integer::sum);
    }
    return count;
}

Step 4: the 2-minute routine

  1. Read the constraints. Write the budget at the top.
  2. Underline the keywords.
  3. Say the brute force out loud in one sentence.
  4. Ask: what work is the brute force repeating? That repeated work is exactly what the pattern removes.
  5. Only then start coding.

Step 4 is the important one. Two pointers removes re-checking pairs you already know are useless. Sliding window removes re-counting the same window. Monotonic stack removes re-scanning to the right. Binary search on the answer removes trying every candidate. Every pattern is a way of not repeating work.

This is not a list to memorise. It is a list to check yourself against after you have solved about 150 questions properly. Ghabrao mat.

Time to read this post: O(1). Time to make it automatic: about 150 well-revised questions.

Written by

Nikhil Sharan

I teach DSA and system design on YouTube (Two Pointers, 1.2M). Ex-SDE at two product companies, now teaching full time. Dry run everything. No paid course here, only free stuff and honest opinions.

Get the best of #interview_horror weekly

One email each Monday with the most useful posts. No spam; unsubscribe in one click.

Comments

35

Sign in to join the conversation.

Sign in to comment
Kunal Bhatia@kunal_dsa#2 in Interview Horror Stories
The "what work is the brute force repeating" question is the single best interview habit. Saving this and sending it to all 14 people I mentor.
13 net votes
Rohit Verma@rohit_codes6 rep in Interview Horror Stories
bhai ye post desi_devs ke har fresher ko bhejna padega. constraints padhna koi nahi sikhata college mein 🙏
13 net votes
Mahin Hasan@mahin_cp#5 in Interview Horror Stories
constraints table is basically what every CF guy does without thinking. two corrections tho: n ≤ 500 can also take O(n² log n) comfortably, and 10^8/sec is for simple ops in C++. python is like 10^7 on a good day
26 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
Correct on both. I kept it rough on purpose, but the Python point matters, so I added a line. Thank you Mahin.
14 net votes
Ankit Khurana@faang_or_bust#9 in Interview Horror Stories
decent list. missing segment tree / BIT for range queries but i guess thats too advanced for the audience
11 net votes
Kunal Bhatia@kunal_dsa#2 in Interview Horror Stories
"too advanced for the audience". Bhai why do you have to add that line every single time
16 net votes
Ankit Khurana@faang_or_bust#9 in Interview Horror Stories
its called being honest. most people here wont see a segment tree in an interview anyway
20 net votes
Mahin Hasan@mahin_cp#5 in Interview Horror Stories
he's not wrong that it's rare in interviews tho. but range sum with updates → BIT is a nice one to add for completeness vai
15 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
Fair. Range queries with updates → Fenwick tree or segment tree. Added it to the list. Rare in Indian SDE-1 interviews, common in OAs from some product companies.
12 net votes
Kelly Zhao@kel_zhao3 rep in Interview Horror Stories
the exactly(k) = atMost(k) - atMost(k-1) trick single-handedly carried me through a co-op OA last year. underrated af 🪿
14 net votes
Sneha Kulkarni@laidoff_not_out#3 in Interview Horror Stories
printing this. i have 6 yrs of react and zero memory of what a heap is. the "constraints → budget" step is the first thing that made dsa feel like reading a spec instead of magic
18 net votes
Kenji Tanabe@kenjitanabe#4 in Interview Horror Stories
Good list. The system design round has an equivalent: read the numbers first (QPS, data size, read/write ratio) and the architecture mostly falls out of them. Same discipline, different round.
16 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
Exactly this. I'm writing that one next, a rate limiter with real numbers. Would love your review before I post it, Kenji.
7 net votes
Kenji Tanabe@kenjitanabe#4 in Interview Horror Stories
Happy to. Send it over.
10 net votes
Sam Whitaker@segfault_sam5 rep in Interview Horror Stories
my 2 minute routine: 1. read constraints 2. panic 3. say "hashmap" confidently 4. it's usually hashmap
19 net votes
Andre Mitchell@andre_3131 rep in Interview Horror Stories
lowkey the "brute force out loud in one sentence" step is exactly what my mentor @renee_em told me before my first tech screen. it works. the interviewer literally relaxed when i did it
19 net votes
Renee Whitfield@renee_em6 rep in Interview Horror Stories
Co-signing from the hiring side: candidates who say the brute force out loud and then improve it score higher on communication, even when they finish later. Fifteen minutes of silence is the hardest thing in the world to score.
9 net votes
Ryan Goh@ai_maxi_ryan4 rep in Interview Horror Stories
or just paste the problem into claude and get the pattern in 2 seconds not 2 minutes 💯
11 net votes
Dana Kowalski@dana_ml4 rep in Interview Horror Stories
In the interview? Bold strategy.
10 net votes
Omkar Joshi@omkar_java4 rep in Interview Horror Stories
Ryan bhau, the OA proctoring software would like a word.
14 net votes
Ryan Goh@ai_maxi_ryan4 rep in Interview Horror Stories
proctoring is cope. companies still doing OAs in 2026 deserve the candidates they get
6 net votes
JoJo Ramos@jojo_navyvet1 rep in Interview Horror Stories
BLUF for career changers: this is the post. Did a bootcamp at 42 and nobody ever told me the constraints were a hint. Bravo Zulu, sir.
12 net votes
Karthikeyan S@karthik_embedded3 rep in Interview Horror Stories
One for embedded folks: when n is small but you have 32KB of RAM, the budget is space, not time. Same habit, read the constraints, just a different column.
16 net votes
박지우@jiwoo_front1 rep in Interview Horror Stories
saved... my junior asked me how to start algorithm study, I will send this
18 net votes
Meenal Deshpande@meenal_restarts4 rep in Interview Horror Stories
Coming back to DSA after a 6 year break, and this is the first cheat sheet that explains why and not only what. PFB my query (haha, old habits): is the prefix sum + hashmap approach expected from freshers or only experienced people? Thank you Nikhil sir.
23 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
Expected from everyone, it is a very common one. And please, just Nikhil 🙂 Welcome back.
15 net votes
Rahul Deshmukh@rahul_d_jobhunt#5 in Interview Horror Stories
laid off SDET here. interviews are asking DSA even for SDET roles now. this list + the 1-3-7-21 revision thing from your older post is my whole plan. day 12 of the plan, still alive
9 net votes
Olivia Martin@liv_codes1 rep in Interview Horror Stories
this is better than the "patterns" doc my uni's CS club passes around, and that one took 4 people a whole semester. sending it to my internship group chat
20 net votes
Zainab Malik@zainab_isb2 rep in Interview Horror Stories
Assalam o Alaikum, I am a 2nd year student from Islamabad. Kindly can you explain once more why sliding window fails with negative numbers? I am having a confusion in the shrinking part.
17 net votes
Kunal Bhatia@kunal_dsa#2 in Interview Horror Stories
Walaikum assalam Zainab. In the window approach you shrink from the left when the sum gets too big, assuming that removing an element makes the sum smaller. With negatives, removing a -3 makes the sum BIGGER, so "shrink when too big" stops being correct. Try [2, -3, 5] with k = 4 by hand and you will see it. That is why prefix sums + hashmap.
10 net votes
Zainab Malik@zainab_isb2 rep in Interview Horror Stories
Ohh. I did it by hand and now I see it. Shukriya so much bhai!
17 net votes
Harshit Gangwar@harshit_20052 rep in Interview Horror Stories
sir i read this 4 times. tier 3 clg, 3rd yr, nobody teaches this in our clg. the constraints table is now my phone wallpaper 😭🙏
19 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
Then you are already ahead of most people. Solve slowly, revise often. You will be fine, Harshit.
11 net votes
Aman Raj@kota_coder_171 rep in Interview Horror Stories
bhaiya i am in class 12 and i understood like 40% of this 😅 but the brute force wala part i understood fully. saving for after jee
18 net votes
Nikhil Sharan@nikhil_twopointers#1 in Interview Horror Stories
40% in class 12 is a great score for this post 😄 JEE first. This will wait for you.
11 net votes