Complexity and Constraints
Estimate whether a solution will run in time from the input size, using Big-O and the rule of thumb of about 10^8 operations per second.
What Big-O counts
Time complexity describes how the number of basic steps grows when the input size n grows. Big-O notation, written , keeps only the fastest-growing term and drops constants. A loop of 3n + 10 steps is .
| Name | Written | Typical source |
|---|---|---|
| constant | a formula, an array lookup | |
| logarithmic | halving the range each step | |
| linear | one loop | |
| linearithmic | sorting | |
| quadratic | two nested loops | |
| cubic | three nested loops | |
| exponential | trying every subset |
Rules you will use daily:
- Sequential loops add; the largest wins. .
- Nested loops multiply: times is .
- Halving or doubling a counter gives . About 30 halvings turn into 1.
Predict the output
What does this print?
int n = 5, cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++) cnt++;
cout << cnt;Predict the output
What does this print?
int cnt = 0;
for (int i = 1; i <= 100; i *= 2) cnt++;
cout << cnt;1 of 8