O(n^2) — Quadratic Time
DSA · Big-O Notationsyntax
Nested loops where both iterate over n. Often a signal to optimize.example
// JavaScript
function hasDuplicateBrute(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) return true;
}
}
return false;
}
# Python
def has_duplicate_brute(arr):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
return True
return Falseoutput
Time: O(n^2) | Space: O(1)Note Bubble sort, selection sort, and insertion sort are all O(n^2). If your brute force is O(n^2), try using a hash map or sorting to bring it down to O(n) or O(n log n). Interviewers often want you to identify the brute force first, then optimize.