You’re a hacker (an ethical one, of course) who’s trying to figure out someone’s password. You decide on a brute-force approach, and write some code that produces every possible string of a given length. Here’s the code you whipped up:

​  ​ def ​ ​ every_password ​(n)
​  ((​ "a" ​ * n)..(​ "z" ​ * n)).​ each ​ ​ do ​ |str|
​  puts str
​  ​ end ​
​  ​ end ​

The way this works is you pass in a number to the function, which becomes the variable n .

If n is 3, for example, the code "a" * n produces the string "aaa" . The code then sets a loop between all possible strings within the range of "aaa" and "zzz" . Running this code will print:

​  aaa
​  aab
​  aac
​  aad
​  aae
​  
​  ...
​  
​  zzx
​  zzy
​  zzz

If n is 4, your code will print all possible strings of length 4:

​  aaaa
​  aaab
​  aaac
​  aaad
​  aaae
​  
​  ...
​  
​  zzzx
​  zzzy
​  zzzz

If you try running this code even for a mere length of 5, you may be waiting quite some time for it to finish. This is a slow algorithm! But how do we express it in terms of Big O?

Let’s break it down.

If we simply print each letter from the alphabet once, it would take 26 steps.

When we print every two-character combination, we end up with 26 characters multiplied by 26 characters.

When printing every three-character combination, we end up with 26 * 26 * 26 combinations.

Do you see the pattern?

Length Combinations
1 26
2 26 2
3 26 3
4 26 4

If we look at this in terms of N, it emerges that if N is the length of each string, the number of combinations is 26 N .

Therefore, in Big O Notation, we express this as O(26 N ). This is an utterly glacial algorithm! The truth is that even an algorithm that is a “mere” O(2 N ) is incredibly slow. Let’s see how it looks on a graph compared to some of the other algorithms we’ve seen so far:

images/big_o_in_everyday_code/different_big_os.png

As you can see, O(2 N ) gets even slower than O(N 3 ) at a point.

In a certain sense, O(2 N ) is the opposite of O(log N). With an algorithm of O(log N) (like binary search), each time the data is doubled, the algorithm takes one additional step. With an algorithm of O(2 N ), each time we add one element of data, the algorithm doubles in steps!

In our password cracker, each time we increase N by one, the number of steps get multiplied by 26. This takes an incredible amount of time, which is why brute force is such an inefficient way to crack a password.