Big O Examples in C++
Big O notation describes how an algorithm’s running time or space usage grows as
the input size π n increases. In C++, you can see common Big O classes like π(1), π(log π), π(π), π(π log π), and π(π 2 ) in simple code patterns and STL operations. Common Big O classes with C++ examples π(1) – Constant time The runtime does not depend on input size.
// Accessing an array element by index
int arr[1000];
int x = arr[5]; // O(1)
// Simple arithmetic / assignment
int y = a + b; // O(1)
bool equal = (a == b); // O(1)
// Push/back on vector (amortized)
std::vector<int> v;
v.push_back(10); // amortized O(1)
Typical π(1) patterns: single statements, no loops depending on π, direct index access, basic arithmetic.
π(π) – Linear time
Runtime grows proportionally with π usually a single loop over all
elements.
// Sum of first n integers (loop version)
int sumOfNumbers(int n) {
int sum = 0;
for (int i = 1; i <= n; ++i) { // runs n times
su…