#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <optional>
// Generic function that works with vectors of any printable/hashable type
template <typename T>
std::optional<T> min_occurrence(const std::vector<T>& vec) {
if (vec.empty()) {
return std::nullopt; // Handle empty vector safely
}
std::unordered_map<T, size_t> counts;
for (const auto& item : vec) {
counts[item]++;
}
auto min_it = std::min_element(
counts.begin(), counts.end(),
[](const auto& a, const auto& b) {
return a.second < b.second;
}
);
return min_it->first;
}
int main() {
std::vector<int> vec = {1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3};
auto result = min_occurrence(vec);
if (result.has_value()) {
std::cout << result.value() << std::endl; // Output: 5
}
}
/*
run:
5
*/