// Function with return valueint add(int a, int b) { return a + b;}// Void function (no return)void printArray(vector<int>& v) { for (int x : v) cout << x << " "; cout << "\n";}// Function with default parametersint power(int base, int exp = 2) { int result = 1; for (int i = 0; i < exp; i++) result *= base; return result;}
// Pass by value — creates a copy (slow for large data)void modify(int x) { x = 10; // Original is NOT changed}// Pass by reference — modifies the original (fast)void modify(int& x) { x = 10; // Original IS changed}// Pass by const reference — fast, read-onlyint sum(const vector<int>& v) { int s = 0; for (int x : v) s += x; return s;}
Always pass vectors and strings by reference (&) to avoid copying. Use const& if you don’t need to modify them.
struct Event { int start, end;};// Custom comparatorbool cmp(Event a, Event b) { return a.end < b.end; // Sort by end time}sort(events.begin(), events.end(), cmp);// Or with lambdasort(events.begin(), events.end(), [](Event& a, Event& b) { return a.start < b.start;});
The rule of thumb: 10⁸ simple operations per second.
n ≤ 10 → O(n!) or O(2ⁿ) is finen ≤ 20 → O(2ⁿ) is finen ≤ 500 → O(n³) is finen ≤ 5000 → O(n²) is finen ≤ 10⁶ → O(n log n) is neededn ≤ 10⁸ → O(n) is neededn > 10⁸ → O(log n) or O(1) is needed
Before coding, always check the constraints and calculate if your approach is fast enough. A TLE (Time Limit Exceeded) means your algorithm is too slow.