DSA Tutorial
🔍

Array Practice Problems

How to Use This Problem List

This list is organized by pattern, not by difficulty. That is intentional.

Most beginners sort by difficulty and try "easy" problems first. The problem is that an easy prefix sum problem and an easy two-pointer problem require completely different thinking. Mixing them teaches you to solve problems randomly rather than recognize patterns.

The better approach: pick one pattern, solve every problem in that section, then move to the next. After finishing a section, you will recognize any problem in that pattern within seconds of reading it.

For each problem, read the title and constraints first. Try to identify the pattern before looking at the hint. If you cannot identify it within 5 minutes, read the hint and try to understand why that pattern applies before coding.

Pattern 1: Single Pass and Basic Traversal

These problems require one traversal of the array with a running variable. The key is knowing what to track at each step.

ProblemDifficultyKey Insight
Find the maximum elementEasyTrack running max, update when current exceeds it
Find the minimum elementEasyTrack running min, update when current is smaller
Calculate array sumEasySingle accumulator, visit every element once
Find second largest elementEasyTrack two running values: first and second
Count elements greater than averageEasyTwo passes: compute average, then count
Find the first missing positiveMediumTreat array as a hash — place each number at its index
Product of array except selfMediumPrefix products forward, suffix products backward
Maximum product subarrayMediumTrack both max and min (negatives can flip sign)

What makes this pattern: you never need to look back at previous elements or look ahead at future ones. The answer builds from a single left-to-right pass.

Complexity target: O(n) time, O(1) space for most.

Pattern 2: Two Pointers

Two pointers reduce pair-checking from O(n²) to O(n) by eliminating sections of the search space with each comparison.

ProblemDifficultyKey Insight
Two Sum II (sorted array)EasySort first, move left up when sum too small, right down when too large
Remove duplicates from sorted arrayEasySlow pointer tracks last unique, fast pointer scans forward
Move zeros to endEasyWrite pointer for next non-zero position, read pointer scans
Valid palindromeEasyLeft and right converge, skip non-alphanumeric
Reverse an arrayEasySwap outer elements, converge inward
3SumMediumFix one element, two-pointer scan for the other two
Container with most waterMediumMove the shorter wall inward — moving the taller can only decrease
Trapping rain waterMediumWater at position i = min(maxLeft, maxRight) - height[i]
4SumMediumFix two elements with two loops, two-pointer for the inner pair
Minimum size subarray sumMediumVariable-size two-pointer: expand right, shrink left

What makes this pattern: two indices, either converging from both ends or moving in the same direction at different speeds. Works best on sorted arrays or when the structure allows you to reason about which pointer to move.

Complexity target: O(n) or O(n log n) with sort.

Pattern 3: Sliding Window

Sliding window maintains a running result across a fixed or variable-size window as it moves from left to right. Each element enters and exits at most once.

ProblemDifficultyKey Insight
Maximum sum subarray of size kEasyFixed window: add right, remove left
Average of subarrays of size kEasyMaintain running sum, divide by k
Longest subarray with sum at most kMediumVariable window: expand right, shrink left when violated
Longest substring without repeating charactersMediumHash set tracks window contents, shrink when duplicate enters
Minimum window substringHardHash map of required chars, shrink when all requirements met
Longest repeating character replacementMediumWindow valid when (length - maxFreq) <= k
Find all anagrams in a stringMediumFixed window of length p, compare frequency maps
Maximum of all subarrays of size kHardMonotonic deque maintains max in O(1) per window

What makes this pattern: the problem asks for an optimal subarray or substring. The words "contiguous," "subarray," "longest," "shortest," "at most k" are the strongest signals.

Complexity target: O(n) time, O(1) or O(k) space.

Pattern 4: Prefix Sum

Precompute cumulative sums to answer range queries in O(1) after O(n) setup.

ProblemDifficultyKey Insight
Range sum queryEasyprefix[r] - prefix[l-1] for any range
Find pivot indexEasyleftSum == totalSum - leftSum - arr[i]
Subarray sum equals kMediumCount prefixes equal to (currentSum - k)
Contiguous array (equal 0s and 1s)MediumReplace 0 with -1, find longest subarray with sum 0
Subarray sums divisible by kMediumTwo subarrays with same (prefix % k) have sum divisible by k
Number of subarrays with product less than kMediumSliding window variant — prefix products
Maximum sum of two non-overlapping subarraysHardPrefix max of fixed-size window sums
Count subarrays with score less than kHardPrefix sum with binary search

What makes this pattern: the problem asks how many subarrays satisfy a sum condition, or queries the sum of arbitrary ranges repeatedly. The word "sum" combined with "equals," "divisible," or "at most" is a strong signal.

Complexity target: O(n) time, O(n) space for the prefix array.

Pattern 5: Sorting and Order

Problems where sorting first unlocks a linear or logarithmic solution that would otherwise be quadratic.

ProblemDifficultyKey Insight
Sort an array (implement)EasyPractice merge sort or quick sort from scratch
Find kth largest elementMediumQuick select O(n) average, or min-heap O(n log k)
Merge sorted arraysEasyTwo-pointer merge, similar to merge sort's merge step
Merge intervalsMediumSort by start, merge overlapping pairs in one pass
Non-overlapping intervalsMediumSort by end, greedily keep intervals that end earliest
Meeting rooms (can one person attend all?)EasySort by start, check for any overlap
Meeting rooms II (min rooms)MediumSort starts and ends separately, two-pointer count
Largest number from array elementsMediumCustom comparator: ab > ba means a comes first
Sort colors (Dutch national flag)MediumThree-way partition with three pointers

What makes this pattern: the problem mentions intervals, or finding an order relationship between elements, or becomes obviously simpler if elements are in sorted order.

Complexity target: O(n log n) for sort-based, O(n) for linear partition.

Pattern 6: Binary Search on Arrays

Binary search applies whenever the answer space or the array itself has a monotonic property.

ProblemDifficultyKey Insight
Binary search (standard)EasyEliminate half the remaining space each step
Find first and last occurrenceMediumBinary search twice — once for left, once for right bound
Search in rotated sorted arrayMediumOne half is always sorted — check which and decide
Find minimum in rotated sorted arrayMediumMinimum is where the sorted order breaks
Find peak elementMediumIf arr[mid] < arr[mid+1], peak is to the right
Search a 2D matrixMediumRow binary search then column, or treat as 1D
Koko eating bananasMediumBinary search on the speed — check feasibility at each mid
Minimum capacity to ship packages in D daysMediumBinary search on capacity — check if D days suffices
Find square root (integer)EasyBinary search on the answer from 1 to n

What makes this pattern: the array is sorted or rotated, or the problem says "minimum X such that condition holds" where the condition is monotonic.

Complexity target: O(log n) per search.

Pattern 7: Hash Map and Hash Set

Use when you need fast lookup by value, frequency counting, or detecting membership.

ProblemDifficultyKey Insight
Two Sum (unsorted)EasyHash map: store complement, check before inserting
Contains duplicateEasyHash set: return true the moment a value is seen again
Find all duplicatesMediumFor each arr[i], negate arr[abs(arr[i])-1]; negatives are duplicates
Longest consecutive sequenceMediumHash set of all values; start chain only if arr[i]-1 not in set
Group anagramsMediumHash map keyed by sorted string or character frequency
First missing positiveMediumRearrange in-place as hash: arr[i] should be i+1
Subarray with zero sumMediumHash set of prefix sums: seen before means zero-sum subarray
Top k frequent elementsMediumHash map frequencies, then heap or bucket sort
Intersection of two arraysEasyHash set of first array, scan second array for matches

What makes this pattern: the problem asks about existence, frequency, or pairing where position does not matter — you need to find elements by value, not by index.

Complexity target: O(n) time, O(n) space.

Pattern 8: In-Place Manipulation

Modify the array itself to encode information, avoiding extra space.

ProblemDifficultyKey Insight
Rotate array by kMediumThree-reversal technique: reverse all, reverse first k, reverse rest
Reverse arrayEasyTwo-pointer swap converging inward
Remove element in-placeEasyWrite pointer for kept elements, overwrite removed positions
Remove duplicates (sorted, in-place)EasyTwo-pointer: slow tracks last unique, fast scans forward
Set matrix zeroesMediumUse first row/col as markers; process them last
Spiral matrixMediumMaintain four boundaries, shrink after each traversal direction
Find the duplicate numberMediumFloyd's cycle detection — treat values as next pointers
Missing numberEasySum formula: n*(n+1)/2 minus actual sum
Single numberEasyXOR of all elements — pairs cancel, singleton remains

What makes this pattern: the problem says "in-place," "O(1) extra space," or the constraint makes allocating a new array impractical.

Complexity target: O(n) time, O(1) space.

Recommended Study Order

If you are starting from scratch, this sequence builds skills progressively without overwhelming you.

Week 1 — Foundation
  Pattern 1 (Single Pass): all problems
  Pattern 8 (In-Place, Easy tier): reverse, remove element, missing number, single number

Week 2 — Core Patterns
  Pattern 2 (Two Pointers): start with Easy, then Medium
  Pattern 3 (Sliding Window): fixed window first, then variable

Week 3 — Precomputation and Search
  Pattern 4 (Prefix Sum): range sum query, subarray sum equals k, pivot index
  Pattern 6 (Binary Search): standard search, first/last occurrence, rotated array

Week 4 — Hash Structures and Harder Problems
  Pattern 7 (Hash Map/Set): two sum, contains duplicate, longest consecutive
  Pattern 5 (Sorting): merge intervals, meeting rooms, sort colors
  Revisit any patterns that felt weak

Problem-Solving Checklist

Before writing any code, run through this checklist:

1. Read the problem until you can restate it without looking.
   → What is the input? What is the exact output?

2. Work through a concrete example by hand.
   → At least one normal case and one edge case.

3. Identify the pattern from the problem's signals.
   → Subarray? → Sliding window or prefix sum
   → Sorted array? → Binary search or two pointers
   → Lookup by value? → Hash map
   → No extra space? → In-place, two pointers

4. State the brute force complexity.
   → Name the bottleneck before optimizing.

5. Apply the pattern to eliminate the bottleneck.
   → State why it works, not just that it does.

6. Verify edge cases: empty array, single element, all same values.
   → Does your solution still produce the correct output?

7. State time and space complexity before submitting.
   → Read the constraint to confirm your complexity is acceptable.

Difficulty Progression Reference

Use this to gauge where you are and what to tackle next.

StageCharacteristicsTarget Problems
BeginnerOne loop, one variable, no index tricksMax, min, sum, reverse
Early IntermediateTwo pointers or sliding window, recognizing patternsTwo Sum, remove duplicates, max sum subarray
IntermediateCombining patterns, e.g. sort + two pointers3Sum, merge intervals, subarray sum equals k
Late IntermediateIn-place tricks, prefix + hash, binary search on answerRotate array, trapping rain water, minimum window substring
AdvancedMultiple data structures, complex invariantsMaximum sliding window, find duplicate, hard prefix problems

Common Interview Topics by Company Focus

Different companies weight different areas. This is general guidance based on observed patterns:

Product-based companies (FAANG-tier):

  • Two Sum variations and hash map patterns appear frequently
  • Sliding window for substring or subarray optimization
  • Merge intervals and scheduling problems
  • Binary search on answer space

Service-based companies and on-campus:

  • Basic traversal and sorting
  • Standard binary search
  • Simple two-pointer problems
  • Array rotation and reversal

Startup interviews:

  • Practical problem-solving: prefix sums, frequency counting
  • In-place manipulation
  • Combined patterns at medium difficulty

Tracking Your Progress

After solving each problem, record:

  1. Pattern used — which of the 8 patterns does this belong to?
  2. Clue that revealed the pattern — what in the problem statement pointed you there?
  3. Time to solve — set a target of 20-30 minutes for medium problems
  4. Edge cases you missed — were there inputs that broke your first solution?

After 30 to 40 problems, review your notes. Look for which patterns you consistently misidentify and which edge cases you repeatedly miss. That tells you exactly what to focus on next.

The goal is not to solve as many problems as possible. It is to build reliable pattern recognition so that any new problem feels familiar within the first two minutes of reading it.