🚀
ArkyEdu BLOG TIC
RO Open App
C++ & Algorithms Grades 7–8 · Olympiad 14 min read

Competitive C++ for Grades 7–8 (Olympiad & High-School Prep): Time Complexity, O(√n) Primes, Frequency Arrays & Binary Search

Stepping up from beginner while loops to competitive programming contests and high-school entrance exams requires moving from „code that passes 10 sample numbers” to „clean algorithms handling 100,000 elements in under 0.1 seconds.” Here is the reference playbook with battle-tested C++ templates.

💬 WhatsApp ← ICT Blog & Guides
Quick Answer (TL;DR)

The gap between a 40-point Time Limit Exceeded and a 100-point Olympiad submission comes down to four core C++ habits: matching your algorithm’s Big-O complexity to N (~10^7–10^8 ops/sec), checking primality in O(√n) with d*d <= n, counting values in O(n) with frequency arrays fr[x]++, and writing bug-free binary search (left <= right, mid = left + (right - left)/2).

1. Estimating Time Complexity Before Writing Line One

Online judges (including the ArkyEdu Olympiad Arena) execute roughly 10^7 to 10^8 simple operations per second. Before picking an approach, always inspect the maximum constraint on N!

Maximum safe time complexity by input size N
Input Constraint NTarget ComplexityTypical C++ PatternExample Algorithm
N ≤ 1,000O(N²)Two nested for loopsBubble Sort, Selection Sort, checking all pairs (i, j)
N ≤ 100,000O(N log N) or O(N)Fast sorting, Binary Search, SieveM binary-search queries, Sieve of Eratosthenes
N ≤ 1,000,000O(N)Single linear scanMin/Max tracking, Frequency arrays, Prefix sums
N ≤ 10⁹ or 10¹²O(√N), O(log N), or O(1)Math, divisors up to √N, Gauss sumO(√N) primality, Euclidean GCD, arithmetic series
Beware of 32-bit int Overflow in d * d <= n!

If n is near 2 billion (2·10^9) and your loop writes for (int d = 3; d * d <= n; d += 2), d * d can overflow 32-bit signed int (max 2,147,483,647) and wrap negative! Always use long long d or 1LL * d * d <= n.

2. O(√N) Primality Testing & The Sieve of Eratosthenes

Beginners test primality by dividing n by every number up to n - 1, taking a million steps when n = 10^6. Because divisors always come in pairs (d, n/d), at least one factor must be ≤ √n—cutting the work down to ~1,000 steps.

When asked to check tens of thousands of numbers up to 1,000,000, precomputing the Sieve of Eratosthenes answers every single query in O(1) instant lookup!

C++ Template: O(√n) isPrime() + Sieve of Eratosthenes
bool isPrime(long long n) {
    if (n < 2) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    for (long long d = 3; d * d <= n; d += 2) {
        if (n % d == 0) return false;
    }
    return true;
}

// Precompute primes up to 100,000 for instant O(1) queries
const int MAXV = 100000;
bool isComposite[MAXV + 1]; // global => zero-initialized (false)
void buildSieve() {
    isComposite[0] = isComposite[1] = true;
    for (int i = 2; i * i <= MAXV; i++) {
        if (!isComposite[i]) {
            for (int j = i * i; j <= MAXV; j += i) {
                isComposite[j] = true;
            }
        }
    }
}
Starting the inner sieve loop at i * i skips multiples already crossed out by smaller primes.

3. Frequency Arrays: Turning Nested Loops into Linear O(N) Speed

A classic contest task asks: „Given N integers between 0 and 1,000 (or digits 0..9), print the most frequent value or output them sorted.”

Instead of O(N²) comparisons, use each input value x directly as the array index in a global counter array: freq[x]++. You get instant counting and sorted traversal in linear time!

C++ Example: Most Frequent Value with a Frequency Array
#include <iostream>
using namespace std;

int freq[1001]; // global => automatically initialized to 0!

int main() {
    int n, x;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> x;
        if (x >= 0 && x <= 1000) freq[x]++;
    }
    int bestVal = 0, maxCount = -1;
    for (int v = 0; v <= 1000; v++) {
        if (freq[v] > maxCount) {
            maxCount = freq[v];
            bestVal = v;
        }
    }
    cout << bestVal << " appears " << maxCount << " times\n";
    return 0;
}
Declaring large arrays outside main() zeroes all slots automatically and avoids stack overflow.

5. The 5-Step Contest Habit & Visual Trace Debugging

Even great algorithms lose points on edge cases (N = 1, x = 0, duplicate numbers, or integer overflow). Build these five contest habits early:

  1. Check numeric bounds first: if a running sum or product can exceed 2·10^9, declare it long long immediately.
  2. Dry-run edge cases on paper: verify N = 0, N = 1, all elements equal, and target smaller/larger than every element.
  3. Keep large arrays global with a small safety buffer (+10 slots above the stated max N).
  4. Step through the first 3 iterations manually (or in ArkyEdu C++ Visual Trace) to watch indices and loop exits.
  5. Never leave prompt text like "Enter N: " in cout—automated judges compare raw output tokens strictly.

✅ Pre-Submission Contest C++ Checklist

  • Large sums and products use long long so 32-bit int cannot overflow.
  • Large arrays are declared globally above main(), never on the function stack.
  • All edge cases (N = 1, 0, duplicates, missing target) were tested without extra cout prompts.
  • Worst-case operation count fits comfortably under ~10^7 operations.

❓ Frequently Asked Questions

Why should large C++ arrays be declared globally outside main()?
The local function stack is small (often 1–8 MB), whereas global static memory holds tens or hundreds of megabytes and automatically initializes all elements to zero.
When should I pick a frequency array instead of sorting?
Use a frequency array whenever values are non-negative integers within a small range (e.g., 0 to 1,000,000). Use standard sorting when values can be negative or up to 10^9.
Why write mid = left + (right - left) / 2 instead of (left + right) / 2?
If left and right are huge integers, adding them can overflow signed 32-bit int into a negative index. Subtracting first completely prevents overflow.
How can students visually trace arrays and loop variables line by line?
Open the ArkyEdu C++ Visual Trace Debugger (/sandbox/?tab=trace) to step through any C++ code line by line while inspecting variable and array states live.
Are there automated Olympiad practice problems on ArkyEdu?
Yes! The ArkyEdu Olympiad Arena (/sandbox/?tab=olympiad) provides 12 progressive C++ problems with hidden automated test suites and instant grading.

More Study Guides

← Back to Blog Index