DSA · Competitive Programmer · Pattern 3 of 9
Constructive Algorithms
15 problems.
Your progress0%
- 1st Visit
- 0/15
- 2nd Visit
- 0/15
- Revise
- 0/15
About this pattern
Constructive problems ask you to build any valid object, such as a permutation, an array, a string or a sequence of operations, rather than compute a single number. There is rarely a standard algorithm; progress comes from solving small cases by hand, spotting an invariant or a pattern, and proving that a simple scheme always works. Useful habits are to derive necessary conditions first, since they often expose the impossible cases, to aim for a canonical intermediate state such as an all-equal or sorted array, and to replay self-inverse operations backwards. Signals: "print any", a bound like "at most 2n operations", or "-1 if impossible". Always test the construction on small inputs.
// Stress-test a construction against brute force for small n
bool valid(const vector<int>& p); // checks the required property
vector<int> construct(int n); // your scheme; empty means "impossible"
bool existsBrute(int n) {
vector<int> p(n);
iota(p.begin(), p.end(), 1);
do { if (valid(p)) return true; } while (next_permutation(p.begin(), p.end()));
return false;
}
void stress() {
for (int n = 1; n <= 8; n++) {
vector<int> p = construct(n);
bool ok = p.empty() ? !existsBrute(n) : valid(p);
if (!ok) cerr << "construction fails for n = " << n << '\n';
}
}