1. Brute Force — Sort & Compare Indices
Intuition
Sort the array in ascending order and check if each element matches its index. If nums[i] != i, then i is the missing number.
Algorithm
- Sort
numsin ascending order. - Loop
ifrom0ton - 1: - If
nums[i] != i, returni. - If loop completes without returning, return
n.
Brute force — search for each expected value
2 of 2 questions left todayThe first expected value is present
The first expected value is present.
#include <algorithm>#include <iostream>#include <vector>using namespace std; // Brute Force: Sort and match indicesint missingNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n; i++) { if (nums[i] != i) { return i; } } return n;} int main() { vector<int> nums = {3, 0, 1}; cout << "Output: " << missingNumber(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Sort & Compare Indices. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Sort & Compare Indices.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.