1. Brute Force — Full History Scan
Intuition
Store all timestamps in a list. Count how many fall in [t - 3000, t].
Algorithm
- Step 1: Append t to timestamps list.
- Step 2: Iterate backwards and count elements >= t - 3000.
- Step 3: Return the count.
#include <iostream>#include <vector> using namespace std; class RecentCounter {private: vector<int> records;public: RecentCounter() {} int ping(int t) { records.push_back(t); int count = 0; int minTime = t - 3000; for (int i = records.size() - 1; i >= 0; --i) { if (records[i] >= minTime) count++; else break; } return count; }}; int main() { RecentCounter rc; cout << rc.ping(1) << endl; // 1 cout << rc.ping(100) << endl; // 2 cout << rc.ping(3001) << endl; // 3 cout << rc.ping(3002) << endl; // 3 return 0;}Time & Space Complexity
- Time complexity:
O(N) per ping— Scans backwards through all past timestamps. - Space complexity:
O(N)— Stores all N historical timestamps.
Why Brute Force Doesn't Scale:
After millions of requests, unbounded arrays crash with out-of-memory errors.
Queue eviction keeps memory strictly under 3001 integers forever.