Writing Test Cases for Array and String Problems
Arrays & HashingModel answerLast updated
Design a systematic testing strategy for array and string coding problems, covering edge cases, validation, and stress testing.
You're working on array and string coding problems in a timed online assessment. The platform provides minimal test cases, and you're responsible for validating your solution against edge cases before submission.
Describe a practical testing strategy that catches common bugs in array and string algorithms. Your approach should cover:
- What categories of edge cases matter most for typical array/string problems
- How to efficiently generate test inputs and verify outputs
- How to catch performance issues before submission
Provide concrete examples showing how you would test two representative problems:
- Finding the maximum sum of any contiguous subarray (non-empty)
- Finding the index of the first character that appears exactly once in a string
Include actual test inputs, expected outputs, and explain what bug each test is designed to catch.
Hints
Hint 1
Start with boundary cases: what happens when the input is empty, has one element, or two elements?
Hint 2
Consider structural patterns: all equal values, sorted order, duplicates, and positions where the answer might appear
Hint 3
Don't compute expected outputs manually for complex cases—write a simple brute-force solution as an oracle
Hint 4
Test performance with maximum-size inputs to catch accidental quadratic operations
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Testing Strategy
Testing during a coding assessment requires speed and coverage. The goal is to catch bugs in 3–5 minutes without manual calculation overhead. A four-layer approach works well:
1. Hand-written boundary cases (the checklist)
Start with 8–12 minimal inputs covering structural patterns. These expose initialization errors, off-by-one bugs, and wrong defaults.
Core categories:
| Pattern | Example | Common bug exposed |
|---|---|---|
| Empty input | [], "" | Index access without length check, wrong default return |
| Single element | [5], "x" | Loops starting at index 1, incorrect range bounds |
| Two elements | [1,2], [2,1] | Sliding window or pointer arithmetic errors |
| All duplicates | [3,3,3], "zzz" | Set-based logic when duplicates are legal |
| Sorted/reverse | [1,2,3], [5,4,3] | Assumptions about input order |
| Negative/zero values | [-5,-2], [0,0,0] | Initializing max/min to 0 instead of first element |
| Answer at boundaries | Result at index 0 or n-1 | Loops that skip first/last position |
| No valid answer | Target not found | Missing the failure case return value |
| Large values | 10**9, 2**31-1 | Integer overflow in fixed-width languages |
| Very large input | n = 100,000 | Quadratic operations that time out |
2. Brute-force oracle
Write an obviously correct O(n²) or O(n³) solution in 2–3 lines. Use it to generate expected outputs for test cases too tedious to compute by hand.
3. Randomized differential testing
Generate 300–500 small random inputs (length ≤ 10, value range like -5 to 5) and compare the fast solution against the oracle. Small inputs with narrow value ranges naturally produce duplicates, sorted sequences, and edge-case shapes.
4. Stress test
Run one maximum-size input and verify it completes within time limits. This catches accidental O(n²) operations like repeated list concatenation or in checks on lists.
Example 1: Maximum Subarray Sum
Problem: Return the maximum sum of any contiguous non-empty subarray.
Hand-written test cases
def max_subarray(nums):
if not nums:
raise ValueError("no non-empty subarray in empty input")
best = current = nums[0] # NOT zero: handles all-negative
for x in nums[1:]:
current = max(x, current + x)
best = max(best, current)
return best
# Edge case table
test_cases = [
([], ValueError), # empty → exception
([7], 7), # single positive
([-4], -4), # single negative (not zero!)
([-3, -1, -5], -1), # all negative → largest element
([0, 0, 0], 0), # all zeros
([2, 2, 2], 6), # all equal
([1, 2, 3, 4], 10), # sorted → sum all
([4, 3, 2, 1], 10), # reverse sorted → sum all
([-2, 3, -1, 2], 4), # mixed: subarray [3, -1, 2]
([5, -100, 6], 6), # answer at end after large negative
([10**9, 10**9], 2*10**9), # large values (overflow check)
]
What each test catches:
- Empty/single: crashes from
nums[0]without checking length - All negative: wrong initialization (
best = 0gives 0, not -1) - Answer at end: loop that stops one element early
Oracle for random testing
def max_subarray_brute(nums):
if not nums:
raise ValueError("no non-empty subarray in empty input")
return max(sum(nums[i:j])
for i in range(len(nums))
for j in range(i+1, len(nums)+1))
# Differential test
import random
rng = random.Random(42)
for _ in range(500):
n = rng.randint(1, 8)
nums = [rng.randint(-3, 3) for _ in range(n)]
assert max_subarray(nums) == max_subarray_brute(nums)
Stress test
import time
large = [random.randint(-1000, 1000) for _ in range(100000)]
start = time.time()
result = max_subarray(large)
elapsed = time.time() - start
assert elapsed < 0.5, f"too slow: {elapsed:.2f}s"
Example 2: First Unique Character Index
Problem: Return the index of the first character that appears exactly once, or -1 if none exists.
Hand-written test cases
from collections import Counter
def first_unique_char(s):
counts = Counter(s)
for i, ch in enumerate(s):
if counts[ch] == 1:
return i
return -1
test_cases = [
("", -1), # empty string
("a", 0), # single character
("aabbcc", -1), # all repeated
("aaaa", -1), # all same
("abcabc", -1), # no unique
("leetcode", 0), # answer at start (l)
("loveleetcode", 2), # answer in middle (v)
("aabbcd", 4), # answer at end (c)
("Aa", 0), # case matters
("😀😀x", 2), # emoji (1 codepoint each)
]
What each test catches:
- Empty/no unique: missing the -1 return path
- Answer at end: loop that doesn't check the last character
- Case sensitivity: using
.lower()when problem expects exact matches - Unicode: assuming 1 char = 1 byte (emoji test confirms correct indexing)
Oracle for random testing
def first_unique_char_brute(s):
for i, ch in enumerate(s):
if s.count(ch) == 1:
return i
return -1
# Differential test with small alphabet → forces duplicates
rng = random.Random(7)
for _ in range(500):
n = rng.randint(0, 10)
s = ''.join(rng.choice('abc') for _ in range(n))
assert first_unique_char(s) == first_unique_char_brute(s)
The narrow alphabet 'abc' ensures most strings have duplicates, testing the counting logic thoroughly.
Stress test
large = ''.join(random.choices('abcdefghij', k=100000))
start = time.time()
result = first_unique_char(large)
elapsed = time.time() - start
assert elapsed < 0.2, f"too slow: {elapsed:.2f}s"
Why This Works
Hand cases define the contract: return types, error conditions, and tie-breaking rules.
The oracle eliminates manual calculation. You write an obviously correct slow version once, then generate hundreds of verified test cases automatically.
Small random inputs over tiny value ranges (e.g., integers in [-3, 3] or alphabet "abc") hit almost every structural pattern at length ≤ 10: duplicates, sorted, all-equal, alternating. Most bugs surface at small n.
The stress test confirms what the oracle cannot: that your solution runs in the expected time complexity on large inputs.
Complexity
- Fast solutions: O(n) time, O(1) or O(k) space (k = distinct characters)
- Oracle per trial: O(n²) or O(n³), but only on n ≤ 10, so 500 trials finish instantly
- Stress test: single O(n) run on n = 100,000
Common Mistakes
- Initializing aggregators to 0 when input can be all-negative (use
nums[0]instead) - Forgetting the "no valid answer" path (return -1, None, or raise an exception as specified)
- Quadratic operations hidden in loops:
list.pop(0),in list, string concatenation with+= - Unicode assumptions: treating multi-byte characters as single bytes, or ignoring case normalization requirements
- Skipping the stress test: the oracle cannot catch timeouts
This entire harness takes 3–5 minutes to write and catches the majority of boundary, logic, and performance bugs before submission.