1. Brute Force — Linear Search for Each 1..N
Intuition
For every integer x from 1 to N, scan the array to verify if x exists. If not found, add x to the result list.
Algorithm
- Initialize an empty list
result. - Loop
xfrom 1 to N. - Set
found = false. - Inner loop through
nums: ifnum == x, setfound = trueand break. - If
foundis false, appendxtoresult. - Return
result.
Brute Force 1..N Membership Linear Scans
2 of 2 questions left todayPhase 1 — 1 is present Do not add to missing list: Step 1: Test integer x = 1
Phase 1 — 1 is present Do not add to missing list: Step 1: Test integer x = 1. Linear scan finds 1 at index 7. Not missing.
#include <iostream>#include <vector>using namespace std; // Brute Force: Check each number from 1 to Nvector<int> findDisappearedNumbers(const vector<int>& nums) { int n = nums.size(); vector<int> result; for (int x = 1; x <= n; x++) { bool found = false; for (int num : nums) { if (num == x) { found = true; break; } } if (!found) { result.push_back(x); // x was not found } } return result;} int main() { vector<int> nums = {4, 3, 2, 7, 8, 2, 3, 1}; vector<int> missing = findDisappearedNumbers(nums); cout << "Missing: ["; for (int i = 0; i < (int)missing.size(); i++) { cout << missing[i] << (i + 1 < (int)missing.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N²)— Outer loop runs N times (for x = 1 to N). Inner loop scans N elements. Total operations = N × N = O(N²). - Space complexity:
O(1) auxiliary— Output list is not counted as auxiliary space. No additional data structures are used.
Why Brute Force Doesn't Scale:
For N = 100,000, checking every number takes 100,000 × 100,000 = 10,000,000,000 operations (10 billion checks), causing TLE.
Key Insight: We are given that numbers are in [1, N]. This means array indices (0 to N - 1) directly correspond to the numbers (1 to N). By negating the value at index (val - 1), we record presence in-place without needing any extra memory.
For N = 105: Brute force takes ~10B ops (TLE). In-place negation takes 2N = 200K ops (~2ms).