1. Brute Force — Linear Search per Consecutive Element
Intuition
For every number, perform a full array linear scan for num+1, num+2, and so on until the consecutive chain terminates.
Algorithm
- Initialize required state variables and allocate data structures for Brute Force — Linear Search per Consecutive Element.
- Iterate through the input array and apply the core algorithmic condition.
- Update boundaries, frequencies, or pointers in accordance with the invariant.
- Return the computed result or transformed array.
Brute Force Linear Search for Consecutive Streaks
2 of 2 questions left todayCandidate 100: Look for 101 in array
Candidate 100: Look for 101 in array. Not found. Streak length is 1.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {private: bool arrayContains(const vector<int>& nums, int target) { for (int x : nums) { if (x == target) return true; } return false; } public: int longestConsecutive(vector<int>& nums) { int longestStreak = 0; for (int num : nums) { int currentNum = num; int currentStreak = 1; while (arrayContains(nums, currentNum + 1)) { currentNum += 1; currentStreak += 1; } longestStreak = max(longestStreak, currentStreak); } return longestStreak; }}; int main() { Solution sol; vector<int> nums = {100, 4, 200, 1, 3, 2}; cout << "Input: [100, 4, 200, 1, 3, 2]\n"; cout << "Brute Force Longest Consecutive: " << sol.longestConsecutive(nums) << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force — Linear Search per Consecutive Element. - Space complexity:
O(1)— Space complexity for Brute Force — Linear Search per Consecutive Element.
Why Brute Force Doesn't Scale:
For N = 100,000, sorting takes ~1,700,000 operations.
Hash Set starter check processes N = 100,000 in ~100,000 lookups (linear runtime).