Chapter 18

Common Patterns & Problem-Solving Strategy

Master the UMPIRE framework and instantly recognize 30+ coding patterns. Learn Toptal's exact evaluation criteria, optimize for every complexity tier, write production-quality code under pressure, and execute a proven 8-week (60-day) study plan covering 75+ must-solve problems.

1400+
Lines of Content
30+
Patterns Covered
75
Problems Mapped
100%
Comprehensive
Table of Contents
18.1

Toptal Coding Test Format

Understand the exact format, evaluation criteria, and scoring methodology. 90 minutes. 3 problems. Precision matters.

Test Structure

AspectDetails
Duration90 minutes total
Problems3 (typically Easy, Medium, Hard)
EnvironmentWeb-based IDE with syntax highlighting
LanguagesC#, Java, Python, JavaScript, Go, C++, Rust
Test CasesVisible + Hidden (no access to hidden until submit)
ResubmissionUnlimited (no penalty)
CompilationReal-time error feedback

Evaluation Rubric (Weighted)

CriterionWeightWhat Reviewers Check
Correctness40%Passes all test cases (visible & hidden). Handles edge cases. Logic is sound.
Efficiency30%Time complexity optimal or near-optimal. Space usage reasonable. No TLE (Time Limit Exceeded).
Edge Cases20%Empty inputs, single element, negatives, overflow, unicode, duplicates, off-by-one. All handled explicitly.
Code Quality10%Clear naming, no magic numbers, helper methods, readable structure, proper formatting.

Time Strategy

Hidden Test Case Patterns

Toptal's hidden tests typically check:

⚠️
Critical: Always solve Easy first to lock in base score. Never spend >40 min on Hard if Medium is unsolved.
18.2

UMPIRE Framework

A six-step methodology that eliminates guessing and reduces careless errors. Follow this for every single problem.

1
Understand — Read problem twice. Identify inputs, outputs, constraints. Ask yourself: What is being asked exactly? Write down 2-3 examples by hand.
2
Match — Recognize the pattern. Look at signal words. Is this two-pointers? Hash map? DP? Trees? Instantly classify into a pattern family.
3
Plan — Write pseudocode. Decide on algorithm. State target time/space complexity. Outline steps without touching the IDE.
4
Implement — Code cleanly. Add brief comments. Use meaningful variable names. Compile and fix syntax errors immediately.
5
Review — Walk through your code line-by-line with example inputs. Spot logical errors. Check boundary conditions. Verify data types.
6
Evaluate — Test with edge cases. Confirm time/space complexity. Run all visible test cases. Submit with confidence.

Worked Example: Two Sum (LeetCode #1)

Problem: Given array of integers and target sum, return indices of two numbers that add to target. Use each element at most once.

Understand
Input: nums=[2,7,11,15], target=9. Output: [0,1] (nums[0]+nums[1]=9). Exactly one solution guaranteed. O(n) time preferred.
Match
Signal: "find pair with property". Hash map pattern. Store num→index, then for each num check if complement exists.
Plan
Iterate through array. For each num, check if (target-num) in dict. If yes, return both indices. Else add num to dict. Time O(n), Space O(n).
Implement
Create Dictionary<int,int>. Loop with index. Check ContainsKey before insertion to handle duplicates.
C#
public int[] TwoSum(int[] nums, int target)
{
    var map = new Dictionary<int, int>();
    
    for (int i = 0; i < nums.Length; i++)
    {
        int complement = target - nums[i];
        if (map.ContainsKey(complement))
            return new int[] { map[complement], i };
        
        if (!map.ContainsKey(nums[i]))
            map[nums[i]] = i;
    }
    return new int[] { };
}
Review
Check complement before adding (correct order). Handle duplicates with ContainsKey check. Clear variable names. No off-by-one errors.
Evaluate
Time: O(n) single pass. Space: O(n) for dict. Optimal for this problem. Ready to submit.
18.3

Pattern Recognition Master Guide (30+ Patterns)

Instantly recognize problem types by signal words. This table is your cheat sheet.

Pattern Signal Words Technique Why It Works LC Examples Chapter
Two PointersSorted, pair, target, reverse, meetingConverging pointers from endsExploit ordering to eliminate binary search#1, #15, #11, #167Ch. 5
Sliding WindowSubarray, substring, longest, shortest, contiguousExpand/contract window with 2 pointersEach element enters/exits once = O(n)#3, #76, #209, #424Ch. 6
Hash MapDuplicate, frequency, count, anagram, complementMap value→count or value→indexO(1) lookup replaces O(n) search#1, #49, #242, #347Ch. 7
Prefix SumSubarray sum, range, cumulative, zero-sumPrecompute cumulative sumsRange sum O(n) → O(1)#303, #560, #724Ch. 9
Binary SearchSorted, find position, log complexity, rotationDivide search space by 2Eliminate half remaining options each step#704, #35, #74, #153Ch. 8
Monotonic StackNext greater, previous smaller, trapping, histogramPush/pop to maintain monotonic orderEach element pushed/popped once = O(n)#20, #155, #739, #84Ch. 10
BFS / QueueShortest path, level order, distance, matrix layersLayer-by-layer exploration with queueGuarantees shortest path in unweighted graph#102, #542, #994, #1091Ch. 13
DFS / RecursionTraversal, path, permutation, reachability, connectedRecursive or stack-based graph traversalExplores all paths; backtracking prunes branches#104, #200, #332, #46Ch. 12
Fast-Slow PointersCycle, middle, kth from end, circular listTwo pointers: one 2x speedFloyd's algorithm: meeting point indicates cycle#141, #142, #876, #202Ch. 11
Tree RecursionDepth, path, LCA, balanced, diameter, subtree sumRecurse on left/right, combine resultsLeverage subtree solutions for superproblems#104, #110, #236, #257Ch. 12
BST PropertySearch tree, validate, in-order, kth, successorIn-order → sorted; use min/max boundsBST property eliminates half of tree#98, #230, #700, #235Ch. 12
Union-FindConnected, components, cycle, grouping, parentMaintain connected components via parent pointersO(α(n)) amortized for find/union#684, #547, #323, #1319Ch. 14
Topological SortPrerequisite, dependency, DAG, ordering, courseKahn (BFS) or DFS for dependency orderDetects cycles; ensures deps processed first#207, #210, #269, #310Ch. 14
DijkstraShortest path, positive weights, weighted graphPriority queue: always process min distanceGreedy: shortest path to node is final#743, #787, #882, #1334Ch. 14
0/1 DPClimb stairs, house robber, partition, maxdp[i]=best solution for subproblem iAvoid recalculating overlapping subproblems#70, #198, #322, #416Ch. 15
Unbounded DPCoin change, unlimited, target sum, combinationsItem can be used multiple timesRecurrence: dp[i] uses all smaller j#322, #518, #494, #377Ch. 15
2D DPEdit distance, unique paths, max square, triangledp[i][j]=solution for subgrid (i,j)2D state space: explore all cell combinations#64, #62, #97, #1143Ch. 15
KnapsackWeight capacity, subset sum, target, boundeddp[i][w]=max value with i items, weight wItem taken or skipped; optimize weight#416, #1049, #474, #494Ch. 15
GreedyInterval, activity, max profit, minimum cost, sortMake locally optimal choice at each stepWorks when greedy leads to global optimum#435, #452, #945, #881Ch. 16
BacktrackingPermutation, combination, subset, N-Queens, SudokuExplore all possibilities; prune invalid branchesSystematically exhaust with early termination#46, #47, #78, #51Ch. 17
Bit ManipulationPower of 2, bit count, XOR swap, subset, maskAND/OR/XOR/shift for compact operationsO(1) bit ops vs. O(n) array ops#191, #231, #136, #268Ch. 4
Math/Number TheoryPalindrome, prime, GCD, Fibonacci, modular, digitApply mathematical insight instead of brute forceSkip redundant computation via math property#204, #172, #69, #1401Ch. 3
Heap / Priority QueueKth largest, median, top K, frequent, min/maxMin/Max heap for quick access to extremeO(log n) insertion; O(1) peak access#215, #295, #347, #313Ch. 10
Graph ColoringBipartite, conflict, map coloring, schedulingAssign colors: no adjacent same colorBFS/DFS detects odd cycles; 2 colors = bipartite#785, #1042, #886, #210Ch. 13
Interval MergingMerge overlapping, non-overlapping, insert, scheduleSort by start; merge if overlappingLinear scan post-sort identifies all overlaps#56, #57, #435, #986Ch. 6
Matrix TraversalSpiral, rotate, search sorted, spiral orderRow-major, spiral, or direction-change iterationLayer-by-layer approach handles complexity#54, #48, #240, #1572Ch. 6
SimulationState machine, game logic, step-by-step, rulesImplement rules directly; iterate stateSometimes no pattern; just simulate correctly#54, #67, #1306, #1849Ch. 2
TrieWord search, autocomplete, prefix, dictionaryTree of characters; each node has childrenO(m) word search vs. O(m log n) hash#208, #211, #212, #1268Ch. 10
Segment Tree/FenwickRange query, point update, sum rectangleBuild tree for fast range aggregationO(log n) query/update vs. O(n) naive#307, #308, #1157, #1606Ch. 10

How to Use This Table

  1. Read problem and highlight keywords
  2. Match keywords to "Signal Words" column
  3. Find the pattern row
  4. Study the "Technique" and "Why It Works" columns
  5. Solve the "LC Examples" problems in that pattern
  6. Reference the chapter for detailed explanation
18.4

Complexity Target Guide

Match input size to target complexity class. This prevents TLE and guides algorithm selection.

Input Size (n)Typical OperationsTarget ComplexityAlgorithm Examples
n ≤ 10~10M opsO(n!) or O(n^6)Brute force all permutations, full backtracking
n ≤ 20~1M opsO(2^n) or O(n^5)Bitmask DP, subset enumeration, exponential
n ≤ 500~250K opsO(n^3) or O(n^2 log n)Floyd-Warshall, DP with 2D state, cubic iteration
n ≤ 10^4~100M opsO(n^2)Nested loops, bubble sort, all pairs
n ≤ 10^5~1B opsO(n log n)Merge sort, heap sort, binary search variants
n ≤ 10^6~1B opsO(n) or O(n log n)Single pass, hash map, sorting, linear scan
n ≤ 10^8~100M opsO(n) onlyMust be linear; very tight constants required
n > 10^8VariesO(log n)Binary search, bit operations, math only

Time Budget Examples

ℹ️
Rule of Thumb: 10^8-10^9 simple operations per second. If uncertain, aim one complexity class better than minimum.
18.5

C# Tips for Competitive Coding

C#-specific tricks to write faster, safer, cleaner code in contests.

Essential Data Structures & Methods

FeatureUsageTime/Space
Dictionary<K,V>Hash map for O(1) lookupO(1) avg, O(n) worst
HashSet<T>Fast membership testing, deduplicationO(1) avg Add/Contains
List<T>Dynamic array, sorted listsO(n) insertion, O(1) access
Queue<T>BFS, level-order traversalO(1) Enqueue/Dequeue
Stack<T>DFS, monotonic stack, parsingO(1) Push/Pop
PriorityQueue<T> (C# 10+)Min/Max heap, DijkstraO(log n) Enqueue/Dequeue
SortedDictionary<K,V>Ordered key access, range queriesO(log n) operations
StringBuilderString concatenation (never use + in loop)O(n) for n appends vs O(n²)
Array.Sort(T[], IComparer)Custom sort order with comparersO(n log n)

Common Patterns & Gotchas

1. StringBuilder for String Building

C# (Bad)
string result = "";
for (int i = 0; i < 1000; i++)
    result += i.ToString(); // O(n²) string copying!
C# (Good)
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
    sb.Append(i); // O(n)
string result = sb.ToString();

2. Dictionary Patterns

C#
// Count frequencies
var freq = new Dictionary<int, int>();
foreach (int num in nums)
    freq[num] = freq.GetValueOrDefault(num, 0) + 1;

// Or use TryGetValue for safety
if (freq.TryGetValue(key, out int val))
    // Use val safely

3. PriorityQueue (C# 10+)

C#
var minHeap = new PriorityQueue<int, int>();
minHeap.Enqueue(5, 5); // value, priority
minHeap.Enqueue(3, 3);
int min = minHeap.Dequeue(); // 3

// For max heap, negate priorities
var maxHeap = new PriorityQueue<int, int>();
maxHeap.Enqueue(5, -5); // negate

4. LINQ Gotchas

5. Span<T> for Performance

C#
// Use Span<T> for zero-copy slicing
int[] arr = new int[] { 1, 2, 3, 4, 5 };
Span<int> slice = arr.AsSpan(1, 3); // No allocation

6. Integer Overflow Safety

C#
// Check bounds before arithmetic
if (a > int.MaxValue - b) // would overflow

// Use long for large intermediate values
long product = (long)a * b;

7. Array.Sort with Custom Comparer

C#
// Sort by custom logic
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));

// Or reverse order
Array.Sort(nums, (a, b) => b.CompareTo(a));

8. Common Math Methods

C#
Math.Abs(x);
Math.Max(a, b); Math.Min(a, b);
Math.Pow(base, exp);
Math.Sqrt(x);
Math.Floor(x); Math.Ceiling(x);
x % m; // modulo
18.6

Edge Cases Master Checklist

These account for 20% of your score. Missing one means wrong answer on hidden tests.

CategoryExamples to TestCode Implications
Empty Input[], "", null, 0 lengthCheck array bounds before access. Handle null gracefully.
Single Elementn=1, one node, one charLoops should handle i=0 case. Base case matters.
DuplicatesAll same value, freq=nDict handling, set dedup, comparison logic.
Sorted/ReverseAscending, descending, already sortedEarly exit conditions, comparison directions.
NegativesAll negative, mixed signs, -1Abs(), sign handling, comparison logic.
ZeroZeros in array, divide by zeroCheck denominator != 0. Handle x=0 specially.
Integer Overflowint.MaxValue, near limitsUse long, check before arithmetic, modulo.
Large Inputn=10^6, stress memoryO(n²) becomes TLE. Use efficient structures.
Off-by-OneBoundary indices, fencepostLoop conditions: i < n vs i <= n. Array indices.
Unicode/Special CharsUTF-8, emoji, accents, newlinesString length vs byte length. Char encoding.
Floating PointNaN, Infinity, roundingEquality checks use epsilon. Integer conversion issues.
Null/Undefinednull references, uninitializedNull checks. Dictionary.TryGetValue not direct access.

Pre-Submission Edge Case Routine

18.7

Code Quality & Refactoring

The final 10% of your score. Clean code reads like prose. Make reviewers happy.

Naming Conventions (C#)

Code Quality Principles

Avoid Magic Numbers
if (i % 2 == 0) is unclear. Better: const int MOD = 2; if (i % MOD == 0). Or comment: // Check if even
Helper Methods
Complex logic in separate methods. IsValid(), GetNeighbors(), Swap() make main logic readable.
Meaningful Comments
Comment the WHY, not the WHAT. // Greedy: always pick min cost option is better than // Loop through array
Consistent Formatting
Proper indentation, spacing around operators, blank lines between logical blocks. Use IDE's formatter.

Before/After Refactoring Example

BEFORE (Poor Quality):

C#
public bool isvalid(string s)
{
    var st = new Stack<char>();
    for(int i=0;i<s.Length;i++)
    {
        char c=s[i];
        if(c=='('||c=='{'||c=='[')st.Push(c);
        else
        {
            if(st.Count==0)return false;
            char t=st.Pop();
            if(!(c==')'&&t=='('||c=='}'&&t=='{'||c==']'&&t=='['))return false;
        }
    }
    return st.Count==0;
}

AFTER (Good Quality):

C#
public bool IsValid(string s)
{
    var stack = new Stack<char>();
    
    foreach (char c in s)
    {
        if (IsOpeningBracket(c))
        {
            stack.Push(c);
        }
        else if (IsClosingBracket(c))
        {
            if (stack.Count == 0 || !IsMatching(stack.Pop(), c))
                return false;
        }
    }
    
    return stack.Count == 0;
}

private bool IsOpeningBracket(char c) => c == '(' || c == '{' || c == '[';

private bool IsClosingBracket(char c) => c == ')' || c == '}' || c == ']';

private bool IsMatching(char open, char close)
    => (open == '(' && close == ')') ||
       (open == '{' && close == '}') ||
       (open == '[' && close == ']');

Quality Checklist

18.8

Top 75 Must-Solve Problems

Solve these and you'll recognize 90% of interview questions. Organized by category and difficulty.

Arrays & Sorting (12 problems)

ProblemLC#DifficultyPatternChapter
Two Sum#1EasyHash Map7
Best Time to Buy & Sell Stock#121EasyDynamic Programming15
Contains Duplicate#217EasyHash Set7
3Sum#15MediumTwo Pointers5
Product of Array Except Self#238MediumPrefix Sum9
Merge Intervals#56MediumInterval Merging6
Search in Rotated Sorted Array#33MediumBinary Search8
Maximum Subarray#53MediumDynamic Programming15
Spiral Matrix#54MediumMatrix Traversal6
Set Matrix Zeroes#73MediumIn-Place Modification2
Rotate Image#48MediumMatrix Rotation6
First Missing Positive#41HardArray Indexing2

Strings (10 problems)

ProblemLC#DifficultyPatternChapter
Valid Parentheses#20EasyStack10
Reverse String#344EasyTwo Pointers5
Longest Substring Without Repeating Chars#3MediumSliding Window6
Group Anagrams#49MediumHash Map7
Valid Palindrome#125MediumTwo Pointers5
Longest Palindromic Substring#5MediumDynamic Programming15
Word Ladder#127MediumBFS13
Edit Distance#72Hard2D DP15
Word Break II#140HardBacktracking DP17
Regular Expression Matching#10Hard2D DP15

Linked Lists (8 problems)

ProblemLC#DifficultyPatternChapter
Reverse Linked List#206EasyLinked List Manipulation11
Merge Two Sorted Lists#21EasyTwo Pointers5
Linked List Cycle#141EasyFast-Slow Pointers11
Add Two Numbers#2MediumLinked List Traversal11
Remove Nth Node From End#19MediumTwo Pointers5
Reorder List#143MediumFast-Slow + Reverse11
Copy List with Random Pointer#138MediumHash Map7
LRU Cache#146HardHash Map + Linked List11

Trees & Graphs (15 problems)

ProblemLC#DifficultyPatternChapter
Binary Tree Inorder Traversal#94EasyTree Traversal12
Invert Binary Tree#226EasyTree Recursion12
Same Tree#100EasyTree Comparison12
Balanced Binary Tree#110EasyTree Recursion12
Lowest Common Ancestor of BST#235EasyBST Property12
Binary Tree Level Order#102MediumBFS13
Binary Tree Zigzag Traversal#103MediumBFS13
Lowest Common Ancestor#236MediumTree Recursion12
Validate BST#98MediumBST Property12
Path Sum II#113MediumBacktracking17
Number of Islands#200MediumDFS/BFS13
Clone Graph#133MediumGraph Traversal13
Course Schedule#207MediumTopological Sort14
Binary Tree Maximum Path Sum#124HardTree Recursion12
Alien Dictionary#269HardTopological Sort14

Dynamic Programming (12 problems)

ProblemLC#DifficultyPatternChapter
Climbing Stairs#70Easy0/1 DP15
House Robber#198Medium0/1 DP15
Coin Change#322MediumUnbounded DP15
Unique Paths#62Medium2D DP15
Partition Equal Subset Sum#416MediumKnapsack15
Word Break#139Medium1D DP15
Longest Increasing Subsequence#300Medium1D DP15
Target Sum#494MediumKnapsack15
Distinct Subsequences#115Hard2D DP15
Interleaving String#97Hard2D DP15
Best Time to Buy Stock IV#188HardDP with State15
Longest Substring w/ At Most K Distinct#340HardSliding Window DP6

Remaining High-Value Problems (18 problems)

ProblemLC#DifficultyPatternChapter
Trapping Rain Water#42MediumMonotonic Stack10
Largest Rectangle in Histogram#84MediumMonotonic Stack10
Kth Largest Element#215MediumHeap/Quickselect10
Top K Frequent Elements#347MediumHeap10
Find Median from Data Stream#295HardHeap10
Meeting Rooms II#253MediumGreedy Sorting16
Interval Scheduling Maximization#452MediumGreedy16
Two Sum III - Data Structure Design#170MediumHash Map7
Sort Colors#75MediumTwo Pointers5
Minimum Window Substring#76HardSliding Window6
Permutations#46MediumBacktracking17
Combinations#77MediumBacktracking17
Subsets#78MediumBacktracking17
Letter Combinations#17MediumBacktracking17
N-Queens#51HardBacktracking17
Sudoku Solver#37HardBacktracking17
Surrounded Regions#130MediumDFS/BFS13
Accounts Merge#721MediumUnion-Find14
18.9

8-Week (60-Day) Study Plan

You have 60 days — use them wisely. This 8-week plan at ~2 hrs/day gives you 120 total hours of deep, structured practice. That's 3x what most candidates invest.

Week 1: Foundations & Big O (Days 1–7)

Goal: Master Big O, arrays, strings, prefix sums. Solve all easy Codility problems. 100% on Codility Lessons 1-5.

Mon: Big O & Complexity (Ch 1). Practice estimating complexity from code snippets. (2 hrs)

Tue: Arrays & Strings (Ch 2). C# arrays, List, StringBuilder. Codility Lessons 1-2. (2 hrs)

Wed: Prefix Sums (Ch 19). Codility Lesson 5. Solve: PassingCars, GenomicRangeQuery, MinAvgTwoSlice. (2 hrs)

Thu: Counting Elements. Codility Lesson 3-4. Solve: MissingInteger, MaxCounters, PermCheck. (2 hrs)

Fri: Practice: Solve 5 easy problems timed (10 min each). Review edge cases. (2 hrs)

Sat: Revisit any problems not at 100%. Write prefix sum template from memory 3 times. (3 hrs)

Sun: Light review. Rest.

Week 2–3: Core Patterns (Days 8–21)

Goal: Master hash maps, two pointers, sliding window, binary search, stacks. Take Mock Test 1.

Week 2 Mon-Fri: Hash Maps (Ch 5), Two Pointers & Sliding Window (Ch 15), Binary Search (Ch 10). 2 problems/day. (2 hrs/day)

Week 2 Sat: Sorting algorithms (Ch 9). Codility Lesson 6. Problems: Distinct, Triangle, NumberOfDiscIntersections. (3 hrs)

Week 3 Mon-Fri: Stacks & Queues (Ch 4). Monotonic stack. Problems: Brackets, Fish, StoneWall, Largest Rectangle, Daily Temperatures. (2 hrs/day)

Week 3 Sat: Review all patterns. Re-solve 5 hardest problems from Weeks 2-3. (3 hrs)

Week 3 Sun: MOCK TEST 1 (90 min timed). Score target: 200+/300. (3 hrs)

Week 4–5: Data Structures Deep Dive (Days 22–35)

Goal: Master trees, graphs, heaps, linked lists. Complete ALL 17 Codility lessons at 100%. Take Mock Test 2.

Week 4 Mon-Wed: Linked Lists (Ch 3). Problems: Reverse, Merge, Cycle Detection, Palindrome. (2 hrs/day)

Week 4 Thu-Sat: Trees & BST (Ch 6). Traversals, Validate BST, LCA, Path Sum, Kth Smallest. (2-3 hrs/day)

Week 5 Mon-Wed: Graphs (Ch 8). BFS, DFS, Dijkstra. Problems: Number of Islands, Course Schedule, Word Ladder. (2 hrs/day)

Week 5 Thu-Fri: Heaps (Ch 7). PriorityQueue. Codility Lessons 8-17 (complete ALL). (2 hrs/day)

Week 5 Sat: Verify ALL 17 Codility lessons are 100%. Fix any that aren't. (3 hrs)

Week 5 Sun: MOCK TEST 2 (90 min timed). Score target: 230+/300. (3 hrs)

Week 6–7: Algorithm Paradigms (Days 36–49)

Goal: Master DP, greedy, backtracking. Solve 50+ medium/hard problems. Take Mock Test 3.

Week 6 Mon-Wed: Dynamic Programming (Ch 12). 1D DP: Climbing Stairs, House Robber, Coin Change, LIS. (2 hrs/day)

Week 6 Thu-Fri: 2D DP: Edit Distance, LCS, Knapsack, Unique Paths. Draw DP tables by hand. (2 hrs/day)

Week 6 Sat: DP Advanced: Stock with Cooldown, Burst Balloons concept, bitmask intro. (3 hrs)

Week 7 Mon-Tue: Greedy (Ch 13): Jump Game, Gas Station, Task Scheduler, Partition Labels. (2 hrs/day)

Week 7 Wed-Thu: Backtracking (Ch 11): Subsets, Permutations, Combination Sum, N-Queens. (2 hrs/day)

Week 7 Fri: Strings, Bit Manipulation, Intervals — solve remaining problems. (2 hrs)

Week 7 Sat: Hard Problem Day: 3 hard problems (1 DP, 1 graph, 1 design). 40 min each. (3 hrs)

Week 7 Sun: MOCK TEST 3 (90 min timed). Score target: 250+/300. (3 hrs)

Week 8+: Polish, Mock Tests & All 4 Rounds (Days 50–60)

Goal: Score 260+/300 consistently. Prepare for all 4 Toptal rounds. Build supreme confidence.

Day 50-51: Weak point audit. Identify 2 weakest categories. Drill those exclusively. (2 hrs/day)

Day 52-53: Speed drills: 6 easy in 60 min, 3 mediums in 75 min. Edge case mastery. (2 hrs/day)

Day 54: Random problem mix from LeetCode — no category chosen. Practice pattern recognition. (2 hrs)

Day 55: MOCK TEST 4 (full simulation, no breaks). Target: 270+/300. (3 hrs)

Day 56: Live Coding prep (REACTO method). Practice talking through solutions aloud. (3 hrs)

Day 57: Take-Home Project prep. Set up .NET template with Clean Architecture, DI, tests. (2 hrs)

Day 58: Communication Round prep. Practice answering common questions aloud. (2 hrs)

Day 59: FINAL MOCK TEST. Dress rehearsal. Score target: 260+/300. (2 hrs)

Day 60: Light review of cheatsheet and golden rules. No new problems. Sleep early. You're ready.

Pro Tip: If stuck on a problem >20 min, read solution/hint, understand, then retry without looking. Solve same problem 3 times on different days = mastery. With 60 days you have time for proper spaced repetition.
18.10

Mock Interview Tips & Time Management

How to think under pressure, communicate, and recover. Master this and you'll ace the real test.

Time Allocation (90 Minutes Total)

Communication Template (Thinking Aloud)

ℹ️
Setup: "Let me make sure I understand the problem. Input: array of integers. Output: two indices. Constraint: use each element once."
ℹ️
Pattern Match: "This looks like a classic hash map problem — find pair with property."
ℹ️
Approach: "My approach: iterate through array, for each element check if complement exists in map. Time O(n), Space O(n)."

When You Get Stuck

Minute 1-5: Reread
Read the problem 2x. Highlight key words. Ask yourself what constraints change the problem.
Minute 6-10: Simplify
Solve the easiest version. E.g., if "subarray", start with "single element". Build up.
Minute 11-15: Pattern Match
Think of 3 similar problems you've solved. What patterns apply? Hash map, two pointers, DP?
Minute 16+: Move On
If still stuck, move to next problem. Partial credit >zero. Try again with fresh eyes later.

Before Final Submission

Pressure Management

18.11

Common Mistakes to Avoid

Learn from others' failures. These 20 mistakes cost interview offers.

MistakeWhy It FailsFix
Skipping edge casesHidden tests catch empty, single element, overflowAlways test: [], [1], max values
Off-by-one errorsLoop conditions wrong; access out of boundsTrace: i < n vs i <= n. Check indices.
Modifying inputProblem says don't modify; you did. Wrong answer.Use auxiliary arrays/maps instead.
Integer overflowa + b overflows to negative; logic breaksUse long, check before arithmetic.
Wrong complexityO(n²) on n=10^5 = TLEMatch input size to complexity target.
Forgetting to returnFunction returns null; crashesCheck all paths return a value.
Mutating shared stateIf multiple test cases, leftover data breaks next testInitialize fresh variables each run.
String concatenation in loopsO(n²) copying; TLEUse StringBuilder.
Assuming sorted inputProblem never says sorted; you assume itReread constraints. Don't assume.
Dictionary access without checkKeyNotFoundException when key missingUse TryGetValue or GetValueOrDefault.
Modifying collection during iterationIndexOutOfRangeException or skip elementsBuild new list or iterate over copy.
Floating-point equality0.1 + 0.2 != 0.3 due to precisionUse epsilon: Math.Abs(a - b) < 1e-9
Not null-checkingNullReferenceException on null inputCheck params: if (s == null) return ...
Wrong complexity analysis"It's O(n)!" but actually O(n²)"Count nested loops, recursion depth.
Not testing with examplesCode passes visible tests, fails hiddenAlways run all provided examples first.
Unclear variable namesReviewers dock points for readabilityUse descriptive names: leftPointer, freqMap
Magic numbers"What does 2 mean?" Code unclearconst int MOD = 2; or comment why.
No comments on complex logicReviewers can't follow intentComment the WHY: "Greedy: pick min..."
Inefficient brute forceCorrect but O(n³); TLEOptimize to O(n log n) or O(n).
Forgetting base case in recursionStack overflow or infinite recursionAlways define: if (n == 0) return ...
⚠️
Critical Mistakes: Off-by-one (50% of bugs), integer overflow (10%), wrong complexity (15%), edge cases (20%). Focus on these.
18.12

Quick Reference Cheat Sheet

One-page summary of critical facts. Print and review 1 hr before test.

Data Structure Operations Complexity

Data StructureAccessSearchInsertDeleteSpace
ArrayO(1)O(n)O(n)O(n)O(n)
Hash TableO(1)O(1)O(1)O(1)O(n)
Linked ListO(n)O(n)O(1)O(1)O(n)
StackO(n)O(n)O(1)O(1)O(n)
QueueO(n)O(n)O(1)O(1)O(n)
Binary TreeO(log n)O(log n)O(log n)O(log n)O(n)
HeapO(1)O(n)O(log n)O(log n)O(n)
Graph (Adjacency List)O(V+E)O(1)O(V)O(V+E)
TrieO(m)O(m)O(m)O(ALPHABET_SIZE * N)

Algorithm Decision Tree

Is the input sorted?

Is it a graph/tree problem?

Can you build optimal solution from subproblems?

Is it a string/substring problem?

Is it an optimization problem (max/min)?

Big O Time Complexity Reference

O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2ⁿ) < O(n!)

Input Size → Target Complexity Quick Map

UMPIRE Framework Summary

  1. Understand — Read 2x, write examples
  2. Match — Recognize pattern type
  3. Plan — Write pseudocode, complexity
  4. Implement — Code cleanly
  5. Review — Walk-through with example
  6. Evaluate — Test edges, confirm complexity

C# Essentials

Final Checklist (5 Min Before Submit)

Final Words: You've prepared well. Trust your training. Follow UMPIRE. Manage time. Think clearly. You will ace this.
Bonus

Advanced Problem-Solving Techniques

Beyond the basics: techniques used by top performers in competitive programming.

Memoization vs. Tabulation

Memoization (Top-Down DP): Start from the problem and recursively solve subproblems, caching results. Easier to code, but risk of stack overflow.

Tabulation (Bottom-Up DP): Build solution from base cases upward. More efficient, no recursion overhead, better for large inputs.

Example: Fibonacci

Memoization:

C#
private int[] memo;
public int Fib(int n)
{
    if (memo[n] != -1) return memo[n];
    if (n <= 1) return n;
    memo[n] = Fib(n - 1) + Fib(n - 2);
    return memo[n];
}

Tabulation:

C#
public int Fib(int n)
{
    int[] dp = new int[n + 1];
    dp[0] = 0; dp[1] = 1;
    for (int i = 2; i <= n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

Backtracking vs. DFS: When to Use Each

DFS (Depth-First Search): General graph/tree traversal. Visit all nodes. Use when you need to explore entire structure.

Backtracking: DFS + constraint checking. Prune branches that violate constraints. Use for permutations, combinations, Sudoku, N-Queens.

Key Difference: Backtracking explicitly undoes choices (removes from current solution set) when backtracking. DFS just visits.

Binary Search Variants

Standard Binary Search: Find exact element in sorted array.

Left Boundary: Find leftmost position of target.

Right Boundary: Find rightmost position of target.

Insert Position: If target not found, return insertion position.

Rotated Array: Find peak or search in rotation point.

Two Pointers: Common Patterns

Converging: Start from both ends, move toward middle. E.g., #1 (Two Sum sorted), #125 (Valid Palindrome).

Fast-Slow: One pointer 2x speed. E.g., #141 (Linked List Cycle), #876 (Middle of Linked List).

Sliding: Both move in same direction, window size varies. E.g., #3 (Longest Substring), #209 (Minimum Subarray).

Graph Traversal Decision Matrix

GoalBFS or DFS?WhyExample
Shortest path (unweighted)BFSGuarantees shortest#127 (Word Ladder)
All pathsDFSExplore all#797 (All Paths)
Connected componentsEitherBoth work; DFS uses less memory#200 (Islands)
Cycle detection (undirected)EitherBoth work#261 (Cycle)
Topological orderDFSNatural fit#207 (Courses)
Shortest path (weighted)DijkstraHandles weights#743 (Network Delay)

DP Optimization Techniques

Space Optimization: If dp[i] depends only on dp[i-1], use rolling array. O(n) space → O(1).

State Compression: Use bitmask for small state. E.g., #1495 (Happy Ending) with n≤20.

Convex Hull Trick: Optimize DP with monotonic property. Advanced, rarely needed in interviews.

Greedy Proof Strategy

When greedy works, prove with exchange argument:

  1. Assume optimal solution differs from greedy
  2. Show you can swap one choice without worsening result
  3. Repeat until greedy choice matched optimal
  4. Conclude greedy is optimal

Example: Activity Selection. Greedy: always pick activity ending earliest. Proof: if optimal picks different first activity, swap it with earliest-ending without losing future activities.

Common Pitfalls by Category

Arrays: Off-by-one in loops, not handling duplicates, modifying input when shouldn't.

Strings: Forgetting about unicode, space vs. trimming, case sensitivity.

Trees: Not handling null children, infinite recursion (missing base case), not checking if BST property holds.

Graphs: Visited set not updated, cycle detection missed, disconnected components ignored.

DP: Wrong subproblem definition, incorrect transitions, base case missing.

Greedy: Forgetting to prove greedy works, edge case where greedy fails.

Performance Optimization Tricks

Constant Factor Improvements:

Interviewer Signals (During Mock/Real Test)

Good signs: Interviewer asking follow-up questions about approach, edge cases, or improvements. Means they're engaged.

Red flags: Long silence. May indicate you're off track. Ask clarifying questions.

Recovery: If stuck, think aloud. "This looks like X, let me try..." Interviewer may nudge you.

How to Use Toptal Resources

Code Review Tab: They show you feedback on past submissions. Learn from it.

Discussion Forum: Read solutions, see different approaches. Don't copy; understand.

Practice Problems: Start easy, progressively harder. Don't skip medium to jump to hard.

Post-Interview Debrief

After each mock or real test:

Last-Minute Cram Sheet

If you have 1 hour before test:

Long-Term Growth Beyond Toptal

After passing Toptal, continue with:

ℹ️
Celebrate Progress: Every problem solved, every pattern mastered, every mock passed—these are wins. Build confidence. You're getting closer.