case studies
An algorithm chapter that never meets a real problem is a gym with no sport This chapter fixes that Two problems from the web, fetched and read, then solved in more than one way with C++
Every solution here compiled with -std=c++23 -Wall -Wextra -Werror and ran against the published examples
No submitted code copied
The problems are the anchor, not the answer
Case one, Codeforces 4A Watermelon
The page tags the problem brute force and math
A watermelon weighs w kilos, 1 <= w <= 100
Two people want two parts, both even, both positive
Print YES if it can be done
The example is 8 -> YES, with 2 + 6 or 4 + 4
Approach one, brute force
bool watermelon_brute(int w) {
for (int a = 1; a < w; ++a) {
int b = w - a;
if (a % 2 == 0 && b % 2 == 0) return true;
}
return false;
}
Try every first part from one to w - 1
Check the other part
This mirrors the statement directly
It is the right first answer because it needs no insight, and at w <= 100 it is cheap enough
Brute force is not shame It is the baseline you compare cleverness against
Approach two, parity
bool watermelon_math(int w) {
return w > 2 && w % 2 == 0;
}
Two even numbers add to an even number
The smallest split into two positive even parts is 2 + 2, so w must be at least four, meaning strictly greater than two
That is the entire condition
This is what the math tag was pointing at
The loop was doing work the arithmetic already knew
Approach three, constructive
std::pair<int, int> watermelon_constructive(int w) {
return {2, w - 2};
}
If the answer is YES, 2 and w - 2 are always valid
The math check says w > 2 and even, so w - 2 is even and positive
No search needed at all
Tradeoffs
| Approach | Cost | What it teaches |
|---|---|---|
| brute force | O(w) | direct translation of the statement |
| parity | O(1) | find the invariant before the loop |
| constructive | O(1) | return the witness, not just YES |
The third version answers a stronger question If you can build the answer, you do not need to prove existence separately
Case two, LeetCode 1 Two Sum
Given an integer array and a target, return the indices of two numbers that add to the target Exactly one solution exists, and you may not reuse an element The page’s follow up asks for better than quadratic time
Examples:
[2,7,11,15] with target 9 gives [0,1]
[3,2,4] with target 6 gives [1,2]
[3,3] with target 6 gives [0,1]
Constraints include length up to 10^4 and values down to -10^9
Those bounds are why the first solution stops being acceptable
Approach one, brute force
std::vector<int> two_sum_brute(const std::vector<int> &nums, int target) {
for (std::size_t i = 0; i < nums.size(); ++i)
for (std::size_t j = i + 1; j < nums.size(); ++j)
if (nums[i] + nums[j] == target)
return {static_cast<int>(i), static_cast<int>(j)};
return {};
}
Every pair, once
Correct, simple, quadratic
At 10^4 that is about fifty million pair checks
The judge will let you know what it thinks of that
Approach two, sort plus two pointers
std::vector<int> two_sum_sort(const std::vector<int> &nums, int target) {
std::vector<std::pair<int, std::size_t>> indexed;
for (std::size_t i = 0; i < nums.size(); ++i)
indexed.emplace_back(nums[i], i);
std::ranges::sort(indexed,
[](const auto &a, const auto &b) { return a.first < b.first; });
std::size_t lo = 0, hi = indexed.size() - 1;
while (lo < hi) {
long long sum = static_cast<long long>(indexed[lo].first) + indexed[hi].first;
if (sum == target)
return {static_cast<int>(indexed[lo].second),
static_cast<int>(indexed[hi].second)};
if (sum < target) ++lo;
else --hi;
}
return {};
}
Keep the original index beside each value before sorting Otherwise you return positions in the sorted array, which is a different problem That mistake is so common it deserves its own badge
The two pointer walk uses the sorted order Too small, move left pointer up Too large, move right pointer down
The long long sum is not decoration
Two values near 10^9 overflow a 32 bit int
C++ will wrap silently and hand you a wrong answer with a straight face
Approach three, one pass hash
std::vector<int> two_sum_hash(const std::vector<int> &nums, int target) {
std::unordered_map<long long, std::size_t> seen;
for (std::size_t i = 0; i < nums.size(); ++i) {
long long need = static_cast<long long>(target) - nums[i];
if (seen.contains(need))
return {static_cast<int>(seen[need]), static_cast<int>(i)};
seen[nums[i]] = i;
}
return {};
}
Store values already visited Ask what value would complete the target If it is present, that pair is the answer
One pass, average constant time per step This is the answer the follow up was fishing for
Tradeoffs
| Approach | Time | Extra memory | What it teaches |
|---|---|---|---|
| brute force | O(n^2) | none | baseline |
| sort and pointers | O(n log n) | O(n) for indexed pairs | order is a resource |
| one pass hash | O(n) average | O(n) | remember what you saw |
The hash version wins on time and uses memory
The sort version is predictable and useful when the data is already sorted
Brute force wins when n is tiny and you want to finish before the coffee cools
How to discuss any new problem
- State the problem in your own words
- Write the brute force version first
- Name the constraint that makes it too slow
- Find the invariant or structure the brute force ignores
- Write the second version
- If you can build a witness, do it
- Compare time, memory, and complexity of the code itself
That is the method from chapter one applied to a real page The contest is not the point The comparison is
Exercises
- Solve Codeforces 4A with the parity check before reading the constructive version
- Break the sort based Two Sum by returning sorted positions instead of original ones
- Find an input where the long long cast matters
- Pick a problem from a contest you follow and write two approaches for it
What to remember
Real problems have constraints Constraints are what turn a correct program into a good one
Posted