1. Remove Duplicates & Sort Descending
Intuition
Insert all elements into a Set to eliminate duplicates, sort in descending order, and return 3rd element (or 1st).
Algorithm
- 1. Collect unique elements into list unique.
- 2. Sort unique descending: unique.sort((a, b) => b - a).
- 3. If unique.length >= 3, return unique[2]; else return unique[0].
Distinct Set + Descending Sort
2 of 2 questions left todayDuplicate numbers are filtered out
Duplicate numbers are filtered out.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: int thirdMax(vector<int>& nums) { set<int, greater<int>> unique(nums.begin(), nums.end()); if (unique.size() < 3) return *unique.begin(); auto it = unique.begin(); advance(it, 2); return *it; }}; int main() { Solution sol; vector<int> nums = {2, 2, 3, 1}; int ans = sol.thirdMax(nums); cout << "Third Max: " << ans << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Deduplication takes O(N) and sorting unique elements takes O(N log N). - Space complexity:
O(N)— Set and unique list take O(N) memory.
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.