1. Brute Force — Check All Pairs
Intuition
Compare each element with every other element using nested loops to detect duplicates.
Algorithm
- Loop with index
ifrom 0 to N - 1. - Nested loop with index
jfromi + 1to N - 1. - If
nums[i] == nums[j], returntrueimmediately. - If all pairs are checked without equality, return
false.
Brute Force All Pairs Equality Scan
2 of 2 questions left todayPhase 1 — No match Advance j to index 2: Pair (0, 1): Fix i=0 (value 1)
Phase 1 — No match Advance j to index 2: Pair (0, 1): Fix i=0 (value 1). Test j=1 (value 2). Elements differ. Increment j.
#include <iostream>#include <vector>using namespace std; // Brute Force: Check all pairsbool containsDuplicate(const vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (nums[i] == nums[j]) { return true; // Duplicate found } } } return false; // All distinct} int main() { vector<int> nums = {1, 2, 3, 1}; cout << "Contains Duplicate: " << (containsDuplicate(nums) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N²)— Compares all pairs (i, j) with j > i, performing N × (N - 1) / 2 comparisons = O(N²) quadratic time. - Space complexity:
O(1)— No auxiliary data structures are used. Memory is strictly constant O(1).
Why Brute Force Doesn't Scale:
For N = 100,000, checking every pair takes (100,000 × 99,999) / 2 ≈ 5,000,000,000 operations (5 billion comparisons), exceeding online judge execution limits.
By leveraging a Hash Set (which has O(1) average lookup), we only need to inspect each number once, finding duplicates in linear O(N) time with immediate early termination.
For N = 105: Brute force takes ~5B ops (TLE). Hash Set takes ~100K ops (~3ms).