Part 11•Chapter 1 of 9•Advanced
Arrays, Strings, Matrices & Pointer Patterns (100 Problems)
Curated 100 benchmark problems spanning prefix sums, sliding window, two pointers, matrices, and string parsing.
~37 min read
7,259 words
8 Sections
Reviewed & Verified (2024 Syllabus)
100 Solved ProblemsOptimal Complexity AnalysisEdge Cases & Gotchas
Mastering linear sequence problem solving requires transitioning from basic syntax to pattern recognition across boundary conditions, in-place index manipulation, and invariant tracking. This volume compiles 100 benchmark interview questions spanning fundamental array algorithms to multi-dimensional matrix operations, complete with optimal time-space targets and edge-case pitfalls.
1. Executive Summary & Learning Objectives
#This problem bank codifies 100 core problems spanning linear arrays, strings, and matrices, organized by structural pattern.
By completing this problem set, you will be able to:
- Recognize Core Algorithmic Patterns: Classify problems into Two Pointers, Sliding Window, Prefix Sum, Difference Array, Kadane's, Dutch National Flag, and Boyer-Moore archetypes.
- Execute In-Place Space Optimizations: Implement pointer swaps, sign tagging, and bitwise arithmetic achieving auxiliary space.
- Formulate Edge-Case Defensive Guards: Handle boundary conditions for empty sequences, duplicates, negative numbers, and matrix coordinate out-of-bounds errors.
- Evaluate Complexity Trade-Offs: Compare time and space costs across hash table lookups ( space), sorting transformations ( time), and monotonic sweeps.
2. Problem Taxonomy & Architecture Guide
#| Section | Problem Range | Primary Patterns Covered | Target Complexity Range |
|---|---|---|---|
| Section 1 | Q001 – Q020 | Array Fundamentals & In-Place Manipulations | Time, to Space |
| Section 2 | Q021 – Q040 | Two Pointers & Inward Convergence | to Time, Space |
| Section 3 | Q041 – Q060 | Sliding Window & Subarray Bounds | Amortized Time, to Space |
| Section 4 | Q061 – Q080 | 2D Matrices, Rotations & Coordinate Traversal | Time, Auxiliary Space |
| Section 5 | Q081 – Q100 | String Processing, Anagrams & Palindromic Partitions | to Time, Space |
Section 1: Array Fundamentals & In-Place Manipulations (Q001 – Q020)
#Q001: Two Sum
- Difficulty:
[Easy]| Pattern:[Hash Map Lookup] - Statement: Given an array of integers
numsand integertarget, return indices of the two numbers that add up totarget. - Optimal Approach: Iterate through
nums, maintaining a hash map of{value: index}. For eachnums[i], check iftarget - nums[i]exists in the map. - Complexity: Time: | Space:
- Edge Cases: Negative numbers, duplicate values, target achievable using the same element twice (prevented by checking index).
Q002: Best Time to Buy and Sell Stock
- Difficulty:
[Easy]| Pattern:[Greedy / Running Minimum] - Statement: Maximize profit by choosing a single day to buy and a single future day to sell.
- Optimal Approach: Track running minimum price seen so far. At each day , compute potential profit
prices[i] - minPriceand update max profit. - Complexity: Time: | Space:
- Edge Cases: Strictly decreasing prices (profit must remain 0), single element array.
Q003: Best Time to Buy and Sell Stock II
- Difficulty:
[Medium]| Pattern:[Greedy Peak-Valley] - Statement: Buy and sell on multiple days to maximize profit (at most 1 share held at any time).
- Optimal Approach: Sum all positive daily price increments: if
prices[i] > prices[i-1], addprices[i] - prices[i-1]to total profit. - Complexity: Time: | Space:
- Edge Cases: Strictly decreasing prices, equal prices consecutively.
Q004: Contains Duplicate
- Difficulty:
[Easy]| Pattern:[Hash Set] - Statement: Return
trueif any value appears at least twice in the array. - Optimal Approach: Insert elements into a hash set; if an element is already present, return
true. - Complexity: Time: | Space:
- Edge Cases: Empty array, all unique elements.
Q005: Contains Duplicate II
- Difficulty:
[Easy]| Pattern:[Sliding Window Hash Set] - Statement: Return
trueifnums[i] == nums[j]and . - Optimal Approach: Maintain a hash set of size at most . Remove
nums[i - k - 1]when sliding window exceeds . - Complexity: Time: | Space:
- Edge Cases: , .
Q006: Product of Array Except Self
- Difficulty:
[Medium]| Pattern:[Prefix & Suffix Products] - Statement: Return an array
outputwhereoutput[i]is the product of all elements exceptnums[i]without using division. - Optimal Approach: Compute prefix products left-to-right into output array, then traverse right-to-left maintaining a running suffix product.
- Complexity: Time: | Space: auxiliary (excluding output array)
- Edge Cases: Multiple zeroes (all outputs 0), single zero (only that index non-zero), negative numbers.
Q007: Maximum Subarray (Kadane's Algorithm)
- Difficulty:
[Medium]| Pattern:[Dynamic Programming / Kadane] - Statement: Find the contiguous subarray with the largest sum.
- Optimal Approach: Maintain
currentSum = max(nums[i], currentSum + nums[i])andmaxSum = max(maxSum, currentSum). - Complexity: Time: | Space:
- Edge Cases: All negative numbers (must return the maximum single negative number).
Q008: Maximum Product Subarray
- Difficulty:
[Medium]| Pattern:[Dual State Kadane] - Statement: Find the contiguous subarray with the largest product.
- Optimal Approach: Maintain both
curMaxandcurMinat each step. Whennums[i] < 0, swapcurMaxandcurMinbefore multiplying. - Complexity: Time: | Space:
- Edge Cases: Array containing zeroes (resets product to 1), odd number of negative values.
Q009: Rotate Array
- Difficulty:
[Medium]| Pattern:[Array Reversal] - Statement: Rotate an array of elements to the right by steps.
- Optimal Approach: Normalize . Reverse the entire array, reverse the first elements, then reverse the remaining elements.
- Complexity: Time: | Space:
- Edge Cases: , , .
Q010: Move Zeroes
- Difficulty:
[Easy]| Pattern:[Two Pointers / Fast-Slow] - Statement: Move all zeroes to the end of the array while maintaining the relative order of non-zero elements.
- Optimal Approach: Slow pointer
insertPostracks position for next non-zero. Fast pointer iterates; when non-zero found, swapnums[insertPos++]withnums[i]. - Complexity: Time: | Space:
- Edge Cases: Array with no zeroes, array with all zeroes.
Q011: Majority Element
- Difficulty:
[Easy]| Pattern:[Boyer-Moore Voting] - Statement: Find the element that appears more than times.
- Optimal Approach: Maintain
candidateandcount. Ifcount == 0, choose current element as candidate. Ifnums[i] == candidate, increment count; else decrement count. - Complexity: Time: | Space:
- Edge Cases: Single element array, majority element appearing exactly times.
Q012: Majority Element II
- Difficulty:
[Medium]| Pattern:[Extended Boyer-Moore] - Statement: Find all elements that appear more than times (at most 2 candidates).
- Optimal Approach: Maintain 2 candidates and 2 counters. Second pass to verify both candidates actually exceed .
- Complexity: Time: | Space:
- Edge Cases: No element meets threshold, 1 element meets threshold, 2 elements meet threshold.
Q013: Missing Number
- Difficulty:
[Easy]| Pattern:[Bit XOR / Gauss Formula] - Statement: Given an array containing distinct numbers in range , find the missing number.
- Optimal Approach: XOR all indices and all array values. Since , the remaining value is the missing number.
- Complexity: Time: | Space:
- Edge Cases: Missing number is 0, missing number is .
Q014: Find All Duplicates in an Array
- Difficulty:
[Medium]| Pattern:[In-Place Index Negation] - Statement: Array of length with numbers in where elements appear once or twice. Find all duplicates in time and space.
- Optimal Approach: For each value , inspect
nums[v - 1]. If already negative, is a duplicate; else negatenums[v - 1]. - Complexity: Time: | Space: auxiliary
- Edge Cases: No duplicates, all numbers duplicated.
Q015: Merge Sorted Array
- Difficulty:
[Easy]| Pattern:[Three Pointers Backward] - Statement: Merge sorted array
nums2intonums1in-place (nums1 has size ). - Optimal Approach: Populate
nums1from the back (index ) by comparing largest remaining elements of both arrays. - Complexity: Time: | Space:
- Edge Cases: (copy all from nums2), (nothing to do).
Q016: Remove Duplicates from Sorted Array
- Difficulty:
[Easy]| Pattern:[Two Pointers Read/Write] - Statement: Remove duplicates in-place such that each unique element appears once. Return count of unique elements.
- Optimal Approach: Slow pointer
k = 0. Fast pointeriscans; whenevernums[i] != nums[k], incrementkand setnums[k] = nums[i]. - Complexity: Time: | Space:
- Edge Cases: Array with all identical elements, all unique elements.
Q017: Remove Duplicates from Sorted Array II
- Difficulty:
[Medium]| Pattern:[Two Pointers with Count Limit] - Statement: Remove duplicates in-place such that duplicates appear at most twice.
- Optimal Approach: For each element in
nums, ifk < 2orx != nums[k - 2], writenums[k++] = x. - Complexity: Time: | Space:
- Edge Cases: Length , all elements equal.
Q018: Next Permutation
- Difficulty:
[Medium]| Pattern:[Lexicographical Permutation Scan] - Statement: Rearrange numbers into the lexicographically next greater permutation.
- Optimal Approach: Scan from right to find first pivot where . From right, find smallest element , swap them, and reverse suffix from to end.
- Complexity: Time: | Space:
- Edge Cases: Array sorted in descending order (reverses to fully ascending).
Q019: Set Matrix Zeroes
- Difficulty:
[Medium]| Pattern:[Matrix In-Place Markers] - Statement: If an element in an matrix is 0, set its entire row and column to 0 in-place.
- Optimal Approach: Use the first row and first column as marker arrays. Use two boolean flags to record whether row 0 and col 0 themselves originally had zeroes.
- Complexity: Time: | Space:
- Edge Cases: Zero at , matrix with only 1 row or 1 column.
Q020: Spiral Matrix
- Difficulty:
[Medium]| Pattern:[Layered Boundary Shrinking] - Statement: Return all elements of an matrix in spiral order.
- Optimal Approach: Maintain four boundaries:
top, bottom, left, right. Traverse right, down, left, up, shrinking boundaries after each direction. - Complexity: Time: | Space: auxiliary
- Edge Cases: Single row matrix, single column matrix, rectangular matrices where .
Section 2: Two Pointer Mastery (Q021 – Q040)
#Q021: Valid Palindrome
- Difficulty:
[Easy]| Pattern:[Two Pointers Inward] - Statement: Check if string is palindrome considering only alphanumeric characters and ignoring cases.
- Optimal Approach: Left and right pointers moving inward, skipping non-alphanumerics and comparing lowercase characters.
- Complexity: Time: | Space:
- Edge Cases: String with no alphanumerics (returns
true), single character.
Q022: Two Sum II - Input Array Is Sorted
- Difficulty:
[Medium]| Pattern:[Two Pointers Inward] - Statement: Find two indices in 1-indexed sorted array that sum to
target. - Optimal Approach: If
nums[left] + nums[right] > target, decrementright; if smaller, incrementleft. - Complexity: Time: | Space:
- Edge Cases: Negative target, exactly 2 elements.
Q023: 3Sum
- Difficulty:
[Medium]| Pattern:[Sort + Two Pointers] - Statement: Return all unique triplets summing to 0.
- Optimal Approach: Sort array. Iterate from 0 to . Skip duplicate . Use two pointers for remaining target , skipping duplicates on matches.
- Complexity: Time: | Space: auxiliary
- Edge Cases: Array with elements, all zeroes
[0, 0, 0], duplicate triplets avoided.
Q024: 3Sum Closest
- Difficulty:
[Medium]| Pattern:[Sort + Two Pointers] - Statement: Find three integers whose sum is closest to
target. - Optimal Approach: Sort array. For each index, use two pointers, updating
closestSumwhenever . - Complexity: Time: | Space:
- Edge Cases: Exact match found (return immediately).
Q025: 4Sum
- Difficulty:
[Medium]| Pattern:[Sort + 2-Loop Two Pointers] - Statement: Return all unique quadruplets summing to
target. - Optimal Approach: Sort array. Nested loops for first two elements with duplicate skipping, then two pointers for remaining two elements.
- Complexity: Time: | Space: auxiliary
- Edge Cases: Integer overflow in sums (use 64-bit integer during sum checks).
Q026: Container With Most Water
- Difficulty:
[Medium]| Pattern:[Two Pointers Greedy] - Statement: Find two lines that together with x-axis form a container holding the most water.
- Optimal Approach: Left at 0, right at . Area is . Always advance the pointer pointing to the shorter height!
- Complexity: Time: | Space:
- Edge Cases: All heights equal, strictly increasing heights.
Q027: Trapping Rain Water
- Difficulty:
[Hard]| Pattern:[Two Pointers Left/Right Max] - Statement: Compute how much water elevation map can trap after raining.
- Optimal Approach: Two pointers with
leftMaxandrightMax. IfleftMax < rightMax, water trapped at left isleftMax - height[left]and advanceleft; else mirror forright. - Complexity: Time: | Space:
- Edge Cases: Monotonically increasing/decreasing slopes (traps 0), flat array.
Q028: Sort Colors (Dutch National Flag)
- Difficulty:
[Medium]| Pattern:[Three-Way Partitioning] - Statement: Sort array of 0s, 1s, and 2s in-place in a single pass.
- Optimal Approach: Pointers
low = 0, mid = 0, high = n - 1. Ifnums[mid] == 0, swap withlow++,mid++. If 1,mid++. If 2, swap withhigh--. - Complexity: Time: | Space:
- Edge Cases: Array with all 0s, all 1s, or all 2s.
Q029: Boats to Save People
- Difficulty:
[Medium]| Pattern:[Greedy Two Pointers] - Statement: Each boat carries at most 2 people under
limit. Find minimum boats. - Optimal Approach: Sort people. Pair heaviest person with lightest if
people[left] + people[right] <= limit. Always place heaviest person on boat (right--). - Complexity: Time: | Space:
- Edge Cases: All people exceed half the limit.
Q030: Squares of a Sorted Array
- Difficulty:
[Easy]| Pattern:[Two Pointers from Ends] - Statement: Given sorted array with negative numbers, return array of squares in sorted order.
- Optimal Approach: Pointers at left and right. Compare and . Place larger square at back of result array.
- Complexity: Time: | Space:
- Edge Cases: All positive numbers, all negative numbers.
Q031: Interval List Intersections
- Difficulty:
[Medium]| Pattern:[Two Pointer Sweepline] - Statement: Find intersections of two closed interval lists.
- Optimal Approach: Intersection is . Valid if . Advance the interval with the smaller endpoint.
- Complexity: Time: | Space: auxiliary
- Edge Cases: Non-overlapping intervals, one interval fully contained in another.
Q032: Remove Element
- Difficulty:
[Easy]| Pattern:[Two Pointers Fast-Slow] - Statement: Remove all instances of
valin-place and return new length. - Optimal Approach: Write pointer
k = 0. Iterate through array; whennums[i] != val, assignnums[k++] = nums[i]. - Complexity: Time: | Space:
- Edge Cases: All elements equal to
val, no elements equal toval.
Q033: Reverse String
- Difficulty:
[Easy]| Pattern:[Two Pointers Swap] - Statement: Reverse an array of characters in-place.
- Optimal Approach: Swap
s[left++]withs[right--]until pointers cross. - Complexity: Time: | Space:
- Edge Cases: Length 0 or 1, even vs odd lengths.
Q034: Reverse Vowels of a String
- Difficulty:
[Easy]| Pattern:[Two Pointers Filtered Swap] - Statement: Reverse only the vowels in a string.
- Optimal Approach: Left and right pointers scanning inward; advance until both point to vowels, then swap.
- Complexity: Time: | Space:
- Edge Cases: No vowels, all vowels, uppercase vs lowercase vowels.
Q035: Valid Palindrome II
- Difficulty:
[Easy]| Pattern:[Two Pointers with 1 Skip] - Statement: Check if string can be palindrome after deleting at most one character.
- Optimal Approach: Inward two pointers. On first mismatch
s[l] != s[r], check if substrings[l+1...r]ORs[l...r-1]is a palindrome. - Complexity: Time: | Space:
- Edge Cases: Already a palindrome, deletion at start vs end.
Q036: Backspace String Compare
- Difficulty:
[Easy]| Pattern:[Two Pointers Backward] - Statement: Compare strings
sandtcontaining'#'(backspace) in space. - Optimal Approach: Traverse both strings backwards, tracking skip counters for active
#characters. - Complexity: Time: | Space:
- Edge Cases: Consecutive backspaces exceeding string length (
"ab##"becomes"").
Q037: Find the Duplicate Number
- Difficulty:
[Medium]| Pattern:[Floyd Cycle Detection] - Statement: Array of integers in range with one duplicate. Find it in time and space without modifying array.
- Optimal Approach: Model as linked list where . Use Tortoise and Hare pointers to find cycle intersection, then reset slow to 0 to find cycle entry.
- Complexity: Time: | Space:
- Edge Cases: Duplicate appears multiple times ( times).
Q038: 4Sum II
- Difficulty:
[Medium]| Pattern:[Hash Map Pair Splitting] - Statement: Given four arrays , find tuples such that .
- Optimal Approach: Compute pairwise sums of and into hash map with frequencies. For pairs in and , query in map.
- Complexity: Time: | Space:
- Edge Cases: All values 0 (combinatorial explosion).
Q039: Longest Mountain in Array
- Difficulty:
[Medium]| Pattern:[Peak Finding Two Pointers] - Statement: Find length of longest mountain subarray (strictly increasing then strictly decreasing, length ).
- Optimal Approach: Identify peak elements where . Expand left and right from each peak to measure mountain length.
- Complexity: Time: | Space:
- Edge Cases: Flat plateaus (invalidates mountain), strictly monotonic arrays.
Q040: Assign Cookies
- Difficulty:
[Easy]| Pattern:[Greedy Two Pointers] - Statement: Maximize number of content children given greed factors and cookie sizes.
- Optimal Approach: Sort both arrays. Match smallest sufficient cookie to the least greedy child using two pointers.
- Complexity: Time: | Space:
- Edge Cases: Cookies all too small, children with equal greed factors.
Section 3: Sliding Window Mastery (Q041 – Q060)
#Q041: Maximum Sum Subarray of Size K
- Difficulty:
[Easy]| Pattern:[Fixed Sliding Window] - Statement: Find maximum sum of any contiguous subarray of size .
- Optimal Approach: Compute sum of first elements. Slide window across: add incoming element and subtract outgoing .
- Complexity: Time: | Space:
- Edge Cases: , .
Q042: Longest Substring Without Repeating Characters
- Difficulty:
[Medium]| Pattern:[Variable Sliding Window] - Statement: Find length of longest substring without repeating characters.
- Optimal Approach: Window . Maintain hash map of character last seen index. When duplicate seen at or after , move .
- Complexity: Time: | Space:
- Edge Cases: Empty string, string of all identical characters.
Q043: Longest Repeating Character Replacement
- Difficulty:
[Medium]| Pattern:[Variable Sliding Window] - Statement: Given string and operations to replace characters, find longest substring with all identical letters.
- Optimal Approach: Window . Track
maxFreqof any character in window. If , shrink window from left. - Complexity: Time: | Space:
- Edge Cases: (entire string can be replaced).
Q044: Minimum Window Substring
- Difficulty:
[Hard]| Pattern:[Variable Sliding Window with Frequency Map] - Statement: Find smallest substring in that contains all characters of including duplicates.
- Optimal Approach: Frequency map of . Expand until window contains all characters (
formed == required). Then contract while window remains valid, updating min window. - Complexity: Time: | Space:
- Edge Cases: No valid window exists (return
""), longer than .
Q045: Permutation in String
- Difficulty:
[Medium]| Pattern:[Fixed Sliding Window Match Count] - Statement: Return
trueif contains a permutation of . - Optimal Approach: Window of size on . Maintain character counts. Track number of matching characters between window and .
- Complexity: Time: | Space:
- Edge Cases: .
Q046: Find All Anagrams in a String
- Difficulty:
[Medium]| Pattern:[Fixed Sliding Window] - Statement: Find all start indices of 's anagrams in .
- Optimal Approach: Fixed window of size . Maintain count arrays for window and . Compare counts at each slide.
- Complexity: Time: | Space:
- Edge Cases: .
Q047: Sliding Window Maximum
- Difficulty:
[Hard]| Pattern:[Monotonic Decreasing Deque] - Statement: Return maximum element in every sliding window of size .
- Optimal Approach: Monotonic deque storing indices with values in decreasing order. Remove elements outside window from front, remove elements smaller than incoming from back.
- Complexity: Time: | Space:
- Edge Cases: , strictly increasing/decreasing array.
Q048: Minimum Size Subarray Sum
- Difficulty:
[Medium]| Pattern:[Variable Sliding Window] - Statement: Return minimal length of contiguous subarray with sum .
- Optimal Approach: Expand adding to running sum. While
sum >= target, record window length , subtract . - Complexity: Time: | Space:
- Edge Cases: Sum of all elements (return 0).
Q049: Fruit Into Baskets
- Difficulty:
[Medium]| Pattern:[At Most K Distinct] - Statement: Find length of longest subarray containing at most 2 distinct integers.
- Optimal Approach: Sliding window with hash map of counts. Shrink whenever
map.size() > 2. - Complexity: Time: | Space: (at most 3 keys)
- Edge Cases: All fruits identical, only 2 types in entire array.
Q050: Max Consecutive Ones III
- Difficulty:
[Medium]| Pattern:[Sliding Window Zero Count] - Statement: Given binary array, find max consecutive 1s if you can flip at most 0s.
- Optimal Approach: Window . Increment
zeroCountwhen . IfzeroCount > k, shrink untilzeroCount <= k. - Complexity: Time: | Space:
- Edge Cases: , array of all 0s.
Q051: Subarrays with K Different Integers
- Difficulty:
[Hard]| Pattern:[Exact K via AtMost(K) - AtMost(K-1)] - Statement: Count contiguous subarrays containing exactly different integers.
- Optimal Approach: Compute
atMost(k) - atMost(k - 1)whereatMost(m)counts subarrays with at most distinct elements in time. - Complexity: Time: | Space:
- Edge Cases: , .
Q052: Count Number of Nice Subarrays
- Difficulty:
[Medium]| Pattern:[Prefix Sum / Sliding Window] - Statement: A subarray is nice if it contains exactly odd numbers.
- Optimal Approach: Replace odd numbers with 1 and even with 0. Reduces directly to Subarray Sum Equals or
atMost(k) - atMost(k - 1). - Complexity: Time: | Space:
- Edge Cases: Array with no odd numbers, exceeds total odd numbers.
Q053: Binary Subarrays With Sum
- Difficulty:
[Medium]| Pattern:[Prefix Sum / Sliding Window] - Statement: Count non-empty subarrays with sum equal to
goalin binary array. - Optimal Approach: Use
atMost(goal) - atMost(goal - 1)sliding window. - Complexity: Time: | Space:
- Edge Cases:
goal = 0.
Q054: Frequency of the Most Frequent Element
- Difficulty:
[Medium]| Pattern:[Sort + Sliding Window Cost] - Statement: Maximize frequency of an element after incrementing elements at most times.
- Optimal Approach: Sort array. Window where cost to make all elements equal to is . If cost , advance .
- Complexity: Time: | Space: auxiliary
- Edge Cases: , all elements already equal.
Q055: Grumpy Bookstore Owner
- Difficulty:
[Medium]| Pattern:[Fixed Sliding Window Improvement] - Statement: Maximize satisfied customers using a secret technique for window to keep owner not grumpy.
- Optimal Approach: Sum all customers where owner is already not grumpy. Use fixed window of size to maximize additional satisfied customers.
- Complexity: Time: | Space:
- Edge Cases: Owner never grumpy, owner always grumpy.
Q056: Subarray Product Less Than K
- Difficulty:
[Medium]| Pattern:[Variable Sliding Window] - Statement: Count contiguous subarrays where product of elements is strictly less than .
- Optimal Approach: If , return 0. Window maintaining product. If product , divide by . Add to answer.
- Complexity: Time: | Space:
- Edge Cases: , , numbers containing 1s.
Q057: Longest Substring with At Most Two Distinct Characters
- Difficulty:
[Medium]| Pattern:[Variable Sliding Window] - Statement: Find length of longest substring with at most 2 distinct characters.
- Optimal Approach: Maintain character counts in hash map. When size , increment until a character count reaches 0 and remove it.
- Complexity: Time: | Space:
- Edge Cases: String length .
Q058: Minimum Window Subsequence
- Difficulty:
[Hard]| Pattern:[Two Pointer Forward-Backward Scan] - Statement: Find shortest substring of containing as a subsequence.
- Optimal Approach: Find match for scanning right in . Once matched, scan backward from rightmost character to find optimal start.
- Complexity: Time: | Space:
- Edge Cases: No valid subsequence exists.
Q059: Maximum Points You Can Obtain from Cards
- Difficulty:
[Medium]| Pattern:[Inverted Sliding Window] - Statement: Pick cards from either end of row to maximize score.
- Optimal Approach: Equivalent to minimizing the sum of an unpicked contiguous subarray of size .
- Complexity: Time: | Space:
- Edge Cases: (sum entire array).
Q060: Defuse the Bomb
- Difficulty:
[Easy]| Pattern:[Circular Fixed Sliding Window] - Statement: Replace each number with sum of next (or previous ) numbers circularly.
- Optimal Approach: If , return all 0s. Maintain sliding window of size over doubled array using modulo arithmetic.
- Complexity: Time: | Space: auxiliary
- Edge Cases: , .
Section 4: Prefix Sum & Difference Arrays (Q061 – Q080)
#Q061: Range Sum Query - Immutable
- Difficulty:
[Easy]| Pattern:[1D Prefix Sum] - Statement: Calculate sum of elements between indices and inclusive in time.
- Optimal Approach: Precompute . Query returns .
- Complexity: Preprocess: | Query: | Space:
- Edge Cases: , .
Q062: Range Sum Query 2D - Immutable
- Difficulty:
[Medium]| Pattern:[2D Prefix Sum] - Statement: Calculate sum of rectangle from to in time.
- Optimal Approach: . Query returns .
- Complexity: Preprocess: | Query: | Space:
- Edge Cases: Querying single cell, querying full matrix.
Q063: Subarray Sum Equals K
- Difficulty:
[Medium]| Pattern:[Prefix Sum + Hash Map] - Statement: Find total number of continuous subarrays whose sum equals .
- Optimal Approach: Maintain running prefix sum . Map stores
{prefixSum: count}, initialized with{0: 1}. Addmap[P - k]to answer. - Complexity: Time: | Space:
- Edge Cases: Negative numbers (prefix sum not monotonic), .
Q064: Continuous Subarray Sum
- Difficulty:
[Medium]| Pattern:[Prefix Sum Modulo Hash Map] - Statement: Return
trueif array has continuous subarray of size summing to a multiple of . - Optimal Approach: Map stores
{prefixSum % k: earliestIndex}. If same remainder seen at index distance, returntrue. - Complexity: Time: | Space:
- Edge Cases: , multiple zeroes consecutively.
Q065: Subarray Sums Divisible by K
- Difficulty:
[Medium]| Pattern:[Prefix Sum Remainder Combinatorics] - Statement: Count contiguous subarrays whose sum is divisible by .
- Optimal Approach: Track frequency of . For frequency , add to answer.
- Complexity: Time: | Space:
- Edge Cases: Negative numbers causing negative remainders.
Q066: Find Pivot Index
- Difficulty:
[Easy]| Pattern:[Running Left Sum vs Total Sum] - Statement: Find index where sum of elements strictly to left equals sum strictly to right.
- Optimal Approach: Compute
totalSum. MaintainleftSum. Pivot condition:leftSum == totalSum - leftSum - nums[i]. - Complexity: Time: | Space:
- Edge Cases: Pivot at index 0 (left sum 0), pivot at index .
Q067: Corporate Flight Bookings
- Difficulty:
[Medium]| Pattern:[Difference Array] - Statement: Given bookings , return total seats booked on each flight .
- Optimal Approach: Difference array . For booking , set and . Take running prefix sum.
- Complexity: Time: | Space:
- Edge Cases: Bookings covering all flights, booking covering single flight.
Q068: Range Addition
- Difficulty:
[Medium]| Pattern:[Difference Array] - Statement: Start with zero array of size . Apply operations .
- Optimal Approach: and . Prefix sum gives final array.
- Complexity: Time: | Space:
- Edge Cases: (do not write out of bounds).
Q069: Car Pooling
- Difficulty:
[Medium]| Pattern:[Difference Array / Bucket Sweepline] - Statement: Check if car with given capacity can pick up and drop off all passengers.
- Optimal Approach: Array of size 1001. Add passengers at
from, subtract atto. Prefix sum must never exceed capacity. - Complexity: Time: | Space: (fixed 1001 buckets)
- Edge Cases: Passenger drop-off happens before pickup at same location.
Q070: Maximum Sum Circular Subarray
- Difficulty:
[Medium]| Pattern:[Kadane Min & Max] - Statement: Find maximum possible sum of non-empty subarray in circular array.
- Optimal Approach: Calculate
maxKadaneandminKadane. Result is . - Complexity: Time: | Space:
- Edge Cases: All elements negative (; return
maxKadane).
Q071: Make Sum Divisible by P
- Difficulty:
[Medium]| Pattern:[Prefix Sum Modulo Subarray] - Statement: Remove smallest subarray so remaining sum is divisible by .
- Optimal Approach: Let target remainder be . Find shortest subarray with sum .
- Complexity: Time: | Space:
- Edge Cases: Remainder is 0 (return 0), cannot remove entire array.
Q072: Count Triplets That Can Form Two Arrays of Equal XOR
- Difficulty:
[Medium]| Pattern:[Prefix XOR] - Statement: Find where .
- Optimal Approach: Condition holds iff prefix XOR . Any between and is valid, contributing triplets!
- Complexity: Time: or with hash map | Space:
- Edge Cases: Entire array XOR equals 0.
Q073: Find Good Days to Rob the Bank
- Difficulty:
[Medium]| Pattern:[Prefix Non-Increasing & Suffix Non-Decreasing] - Statement: Day is good if prices are non-increasing for days before and non-decreasing for days after.
- Optimal Approach: Precompute
left[i](consecutive non-increasing steps before ) andright[i](consecutive non-decreasing after ). Good if both . - Complexity: Time: | Space:
- Edge Cases: (all days valid).
Q074: Number of Submatrices That Sum to Target
- Difficulty:
[Hard]| Pattern:[2D to 1D Prefix Sum] - Statement: Count submatrices that sum to target.
- Optimal Approach: Fix top and bottom row pairs . Compress column sums between them into a 1D array, reducing to Subarray Sum Equals .
- Complexity: Time: | Space:
- Edge Cases: Target is 0, matrix with negative values.
Q075: Matrix Block Sum
- Difficulty:
[Medium]| Pattern:[2D Prefix Sum] - Statement: Return matrix
answhereans[i][j]is sum of elements in . - Optimal Approach: Precompute 2D prefix sums. Clamp coordinates to matrix bounds and query in .
- Complexity: Time: | Space:
- Edge Cases: larger than matrix dimensions.
Q076: Maximum Size Subarray Sum Equals K
- Difficulty:
[Medium]| Pattern:[Prefix Sum Earliest Index] - Statement: Find max length of subarray summing to .
- Optimal Approach: Map stores
{prefixSum: earliestIndex}. When exists in map, updatemaxLen = max(maxLen, i - map[P - k]). - Complexity: Time: | Space:
- Edge Cases: No subarray sums to .
Q077: Splitting a String Into Descending Consecutive Values
- Difficulty:
[Medium]| Pattern:[Backtracking / String Parsing] - Statement: Check if string can be split into substrings with values strictly decreasing by 1.
- Optimal Approach: Try all valid first numbers. Backtrack to verify subsequent adjacent numbers match .
- Complexity: Time: | Space:
- Edge Cases: Leading zeroes, large numbers requiring 64-bit integer.
Q078: Minimum Penalty for a Shop
- Difficulty:
[Medium]| Pattern:[Prefix 'N' & Suffix 'Y' Counts] - Statement: Find earliest closing hour minimizing penalty ('Y' after close + 'N' before close).
- Optimal Approach: Precompute suffix count of 'Y' and prefix count of 'N'. Iterate through closing hours to find minimum penalty.
- Complexity: Time: | Space:
- Edge Cases: Closing at hour 0 vs hour .
Q079: Shifting Letters
- Difficulty:
[Medium]| Pattern:[Suffix Sum on Shifts] - Statement: Shift first letters by
shifts[i]. Return resulting string. - Optimal Approach: Shifts accumulate from right to left! Take suffix sum of shifts modulo 26, then shift each character by
totalShift[i]. - Complexity: Time: | Space: auxiliary
- Edge Cases: Very large shift values (exceeding ; use modulo 26).
Q080: Check If Array Pairs Are Divisible by K
- Difficulty:
[Medium]| Pattern:[Remainder Frequency Pairing] - Statement: Can array be paired such that sum of each pair is divisible by ?
- Optimal Approach: Count remainders modulo . Frequency of remainder 0 must be even; for , frequency of must equal frequency of .
- Complexity: Time: | Space:
- Edge Cases: Negative numbers, is even ( frequency must be even).
Section 5: String Algorithms & Palindromes (Q081 – Q100)
#Q081: Valid Anagram
- Difficulty:
[Easy]| Pattern:[Frequency Array Count] - Statement: Given two strings and , return
trueif is an anagram of . - Optimal Approach: Array of size 26. Increment for , decrement for . All counts must equal 0.
- Complexity: Time: | Space:
- Edge Cases: Strings of different lengths.
Q082: Group Anagrams
- Difficulty:
[Medium]| Pattern:[Sorted String / Frequency Key Hash Map] - Statement: Group an array of strings into anagram clusters.
- Optimal Approach: For each word, use sorted word (or 26-character frequency tuple) as key in hash map.
- Complexity: Time: | Space:
- Edge Cases: Empty strings
"", single character strings.
Q083: Longest Common Prefix
- Difficulty:
[Easy]| Pattern:[Vertical Character Scanning] - Statement: Find longest common prefix string amongst an array of strings.
- Optimal Approach: Compare characters column by column across all strings until mismatch or end of shortest string.
- Complexity: Time: | Space:
- Edge Cases: Empty array, no common prefix.
Q084: String to Integer (atoi)
- Difficulty:
[Medium]| Pattern:[State Machine / Overflow Handling] - Statement: Parse string into 32-bit signed integer handling whitespace, sign, and clamp on overflow.
- Optimal Approach: Skip leading spaces. Check
+or-. Parse digits, checkingparsed > (INT_MAX - digit) / 10to clamp before overflow. - Complexity: Time: | Space:
- Edge Cases: Integer overflow/underflow, non-digit characters following valid digits.
Q085: Longest Palindromic Substring
- Difficulty:
[Medium]| Pattern:[Expand Around Center] - Statement: Find longest palindromic substring in .
- Optimal Approach: Expand around centers (each character for odd palindromes, each gap for even palindromes).
- Complexity: Time: | Space:
- Edge Cases: String with all identical characters, single character string.
Q086: Palindromic Substrings
- Difficulty:
[Medium]| Pattern:[Expand Around Center] - Statement: Count total number of palindromic substrings.
- Optimal Approach: For each of the centers, expand outward, incrementing count while characters match.
- Complexity: Time: | Space:
- Edge Cases: Single character string (count 1).
Q087: Count and Say
- Difficulty:
[Medium]| Pattern:[Run-Length Encoding Simulation] - Statement: Generate the -th term of the count-and-say sequence.
- Optimal Approach: Iteratively transform string: scan contiguous blocks of identical digits, append
countthendigit. - Complexity: Time: upper bound | Space:
- Edge Cases: (base case
"1").
Q088: Minimum Insertion Steps to Make a String Palindrome
- Difficulty:
[Hard]| Pattern:[LCS with Reversed String] - Statement: Find minimum characters inserted to make string a palindrome.
- Optimal Approach: .
- Complexity: Time: | Space:
- Edge Cases: String already a palindrome (returns 0).
Q089: Longest Happy Prefix
- Difficulty:
[Hard]| Pattern:[KMP $\pi$ Table] - Statement: Find longest prefix that is also a suffix (excluding string itself).
- Optimal Approach: Compute KMP LPS array . Return prefix of length .
- Complexity: Time: | Space:
- Edge Cases: No valid prefix-suffix (returns
"").
Q090: Repeated Substring Pattern
- Difficulty:
[Easy]| Pattern:[String Doubling / KMP] - Statement: Check if string can be constructed by repeating a substring.
- Optimal Approach: Check if is a substring of .
- Complexity: Time: | Space:
- Edge Cases: Single character string (returns
false).
Q091: Multiply Strings
- Difficulty:
[Medium]| Pattern:[Elementary School Multiplication Array] - Statement: Multiply two non-negative integers represented as strings without big integer libraries.
- Optimal Approach: Allocate array of size . Digits contribute to indices (carry) and .
- Complexity: Time: | Space:
- Edge Cases: Either string is
"0".
Q092: Add Strings
- Difficulty:
[Easy]| Pattern:[Column Addition with Carry] - Statement: Add two non-negative integer strings.
- Optimal Approach: Two pointers from right ends, add digits with carry, prepend to result.
- Complexity: Time: | Space: auxiliary
- Edge Cases: Unequal lengths, final leftover carry .
Q093: Compare Version Numbers
- Difficulty:
[Medium]| Pattern:[Two Pointer Delimiter Parsing] - Statement: Compare version strings
version1andversion2split by'.'. - Optimal Approach: Parse numerical chunk between dots in both versions. Compare integer values (treating missing chunks as 0).
- Complexity: Time: | Space:
- Edge Cases: Leading zeroes (
"1.01"equals"1.1"), trailing zeroes ("1.0"equals"1").
Q094: Reverse Words in a String
- Difficulty:
[Medium]| Pattern:[Word Inversion Two Pointers] - Statement: Reverse words in string, removing leading, trailing, and multiple spaces.
- Optimal Approach: Reverse entire string, reverse each individual word, and clean up spaces in-place.
- Complexity: Time: | Space: in mutable languages
- Edge Cases: Multiple consecutive spaces, leading/trailing whitespace.
Q095: Basic Calculator II
- Difficulty:
[Medium]| Pattern:[Stack / Running Evaluation] - Statement: Evaluate string expression containing
+,-,*,/and non-negative integers. - Optimal Approach: Track current number and previous sign. For
*and/, resolve immediately with top of stack. Sum stack at the end. - Complexity: Time: | Space:
- Edge Cases: Multi-digit numbers, spaces interspersed throughout.
Q096: Minimum Deletions to Make Character Frequencies Unique
- Difficulty:
[Medium]| Pattern:[Greedy Hash Set] - Statement: Delete minimal characters so no two letters have same non-zero frequency.
- Optimal Approach: Count frequencies. Decrement duplicate frequencies until unused or 0 using a hash set.
- Complexity: Time: | Space:
- Edge Cases: Many characters with frequency 1.
Q097: Decode String
- Difficulty:
[Medium]| Pattern:[Dual Stack (Counts & Strings)] - Statement: Decode pattern where encoded string inside brackets is repeated times.
- Optimal Approach: When
[seen, push current multiplier and current string onto stacks. When]seen, pop multiplier and append repeated substring. - Complexity: Time: | Space:
- Edge Cases: Nested brackets
3[a2[c]], multi-digit repeat counts10[a].
Q098: Custom Sort String
- Difficulty:
[Medium]| Pattern:[Counting Sort by Order Map] - Statement: Sort characters of according to custom order given in string
order. - Optimal Approach: Count frequencies of characters in . Output characters in sequence of
order, then append remaining unmentioned characters. - Complexity: Time: | Space:
- Edge Cases: Characters in not present in
order.
Q099: Reorganize String
- Difficulty:
[Medium]| Pattern:[Max-Heap / Parity Placement] - Statement: Rearrange characters so no two adjacent characters are identical.
- Optimal Approach: If most frequent character , impossible. Place most frequent character at even indices , then fill remaining.
- Complexity: Time: | Space:
- Edge Cases: Impossible configurations where max frequency exceeds .
Q100: Word Pattern
- Difficulty:
[Easy]| Pattern:[Bijection Dual Hash Map] - Statement: Check if string follows the same pattern as string .
- Optimal Approach: Bijective mapping: map character word and word character. Both mappings must remain consistent.
- Complexity: Time: | Space:
- Edge Cases: Unequal number of words and pattern characters.
References & Academic Attribution
#- Skiena, S. S. (2020). The Algorithm Design Manual (3rd ed.). Springer.
- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.). MIT Press.
- USA Computing Olympiad (USACO) & CP-Algorithms Archives (2024). Curated Competitive Programming and Algorithm Verification Standards.