How to calculate O notation and algorithm complexity
Tags: algorithms, order
Published: 2022-01-17 15:49:56

# Overview
This article is a translation of [O（オーダー）記法とアルゴリズムの計算量の求め方
](https://bmf-tech.com/posts/O%EF%BC%88%E3%82%AA%E3%83%BC%E3%83%80%E3%83%BC%EF%BC%89%E8%A8%98%E6%B3%95%E3%81%A8%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0%E3%81%AE%E8%A8%88%E7%AE%97%E9%87%8F%E3%81%AE%E6%B1%82%E3%82%81%E6%96%B9).
We will summarize the prerequisite knowledge about the O notation that roughly calculates the calculation performance of the algorithm and how to calculate the amount of calculation.

# What is the amount of calculation (order)?
An index that expresses the calculation performance of the algorithm as the ratio of how much the execution time increases to the increase in the amount of data.
- Time complexity
 - processing time
- Spatial complexity
 - memory usage

# Big O/Big θ/Big Ω
Each describes the calculation time, but summarizes the differences in academic meaning.

- Big O
  - Upper limit of calculation time
- Big θ
  - Lower limit of calculation time
- Big Ω
  - Both O and Ω

# Best/Worst/Expected Case
We will summarize the three patterns that represent the execution time of the algorithm.

- Best case
 - Lower limit of computational complexity. The case where the values ​​of all elements are equal. There is not much discussion because the value is far from the worst case and the expected case, and it is usually the case that can be executed with O (₁).
- Worst case
 - Upper limit of computational complexity.
- Expected (average) case
 - Average amount of calculation. The case where the value of the element is average.

For many algorithms, the worst case and the expected case are often the same. It was

# O notation

The representative ones are summarized in the order of the shortest processing time.

| O notation | Names in theory of computation | Overview |
| --- | --- | --- |
| O (₁) | Constant time | Processing time does not increase even if the amount of data increases |
| O (log n) | Logarithmic time | Calculation time hardly increases even if the amount of data increases. Even if it increases, the increase in the amount of calculation becomes smaller. |
| O (n) | Linear time | Processing time increases as the amount of data increases |
| O (n log n) | Semi-linear, linear logarithmic time | Slightly heavier than O (n) |
| O (n²) | Squared time | Processing such as checking all combination pairs from elements. As the amount of data increases, the amount of calculation increases. |
| O (n³) | Polynomial Time | Triple Loop |
| O (kⁿ) | Exponential time | Processing to get all combinations from elements |
| O (n!) | Factorial time | It takes time proportional to the factorial of n |

# How to calculate the amount of calculation
Calculate the number of steps and calculate the amount of calculation based on the total.
The following two points are of low importance when calculating the amount of calculation, so they are omitted.

- Omit other than the maximum degree term
 - O (n² + n)
  - O (n²)
- Omit the coefficient
 - O (2n)
  - O (n)

Whether to add or multiply the processing execution time in the step calculation depends on whether each processing occurs at the same time or not.

If it does not happen at the same time, add the execution time.

```js
for (condition) {
  // do something
}

for (condition) {
  // do something
}
```

If it happens at the same time, it takes time to execute.

```js
for (condition) {
  for (condition) {
    // do something
  }
}
```

## example
### Linear search

```js
const targetData = 4; // Run once
const data = [1, 2, 3, 4, 5]; // Run once

for (let i = 0; i <data.length; i ++) {
if (targetData == data [i]) {
  console.log (`$ {i} th found data`); // data.length executed times → executed n times
    return;
  }
}

console.log ('No desired data'); // Run once
```

In the case of the above code, the total number of steps is 1 + 1 + n + 1 = 3n.
Since the coefficient is excluded, the amount of calculation is O (n).

### for statement dual structure

```js
const data = [1, 2, 3, 4, 5]; // Run once

for (let i = 0; i <data.length; i ++) {
console.log (`$ {i} th process`); // Executed once
for (let j = 0; j <data.length; j ++) {
console.log (j); // 4 * Executed 4 times → Executed n² times
  }
}
```

In the above case, the number of steps is 1 + 1 + n² = 2n², so the amount of calculation is O (n²) excluding the coefficient.

### Algorithms whose computational complexity is logarithmic

```js
const n = 10; // executed once

for (let i = 0; i <n; i = i * 2) {
  console.log (i ++); // log2 ⁿ Executed times
}
```

When n is 1
Number of loops 1

When n is 4
Number of loops 2

When n is 8
Number of loops 3

The number of loops is calculated by log2ⁿ.
Since the number of steps is 1 + log2ⁿ, the amount of calculation is log n, omitting various things.


# Reference link
- [計算量オーダーについて](https://qiita.com/asksaito/items/59e0d48408f1eab081b5)
- [[初心者向け] プログラムの計算量を求める方法](https://qiita.com/cotrpepe/items/1f4c38cc9d3e3a5f5e9c)
- [[初心者向け] プログラムの計算量を求める方法](https://qiita.com/cotrpepe/items/1f4c38cc9d3e3a5f5e9c)
- [計算量オーダーの求め方を総整理！ 〜 どこから log が出て来るか 〜](https://qiita.com/drken/items/872ebc3a2b5caaa4a0d0)
- [techscore - 開発新卒に捧ぐ、基本のアルゴリズムと計算量](http://www.techscore.com/blog/2016/08/08/%E9%96%8B%E7%99%BA%E6%96%B0%E5%8D%92%E3%81%AB%E6%8D%A7%E3%81%90%E3%80%81%E5%9F%BA%E6%9C%AC%E3%81%AE%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0%E3%81%A8%E8%A8%88%E7%AE%97%E9%87%8F/)

# Reference books
- [世界で闘うプログラミング力を鍛える本 ~コーディング面接189問とその解法~](https://amzn.to/2yOgQ08)
- [アルゴリズム図鑑 絵で見てわかる26のアルゴリズム](https://amzn.to/2SVXD3p)
- [プログラミングコンテスト攻略のためのアルゴリズムとデータ構造](https://amzn.to/2WTJm8C)
- [アルゴリズムを、はじめよう](https://amzn.to/35SiHxa)
- [Web+DB press vol.91 2016](https://amzn.to/2y0zcea)