Big O Notation: Quadratic Time

Dean
2 min readAug 23, 2020

Within the scope of “Big O”, quadratic time isn’t the worse possible time you can have, but its still very bad. Often times quadratic time can also be thought of the “brute force” method of solving problems, if you’ve ever seen a password cracker in the movies its more than most likely running at Quadratic Time.

Speaking of password cracking! Imagine you are a hacker trying to crack into the administrative site of you local bank. You open up your laptop and begin to hack into the bank’s site as the manager of the site. (For simplicity lets say we at least know the managers username, and his password is exactly 5 characters).

You write an algorithm to go through each alpha-numeric character for each of the 5 positions until you get a match. The problem can be seen as:

// this would be the password we are trying to crack
const currentPassword = 'Easy1'
// and these would be the characters we'd have to loop through
const possibleCharacters = [A...Z, a...z, 0-9]

So far we have a string and an array to loop through:

//we set an empty array for the "cracked password"
let crackedPassword = []
//Begin to loop through the currentPassword
for(let i = 0; i < currentPassword.length, i++){
//And then loop through the possibleCharacters
for(let j = 0; j < possibleCharacters.length, j++){
//If the character at currentPassword[i] matches the
//character at possibleCharaters[j]...
if(currentPassword[i] === possibleCharacters[j]){
//add that Character to the crackedPassword array
crackedPassword.push(possibleCharacters[j])
}
}
return crackedPassword
}

(Technically since we’re using 2 different loops in this example, the Big O of our algorithm would actually equal O(a * b) which is a really similar time to O(n²). If we were using the same loop twice it would calculate to O(n²))

For each additional character in our ‘currentPassword’ string we have to compare that character to every character in our ‘possibleCharacters’ array. To find the time it takes to complete the operation we would have to multiply the characters in our ‘currentPassword’ string to the charaters in our ‘possibleCharaters’ string. If we roughly work out the number of operations performed in the above example it would equal to 33,800. If the password was one character longer it would roughly equal 40,560 operations.

--

--