Difficulty: Easy
Hello, I’m back… This isn’t the daily question but from the Neetcode 150 Roadmap. I’m going to start doing these everyday for practice and to help peeps starting out.
The first few days are going to probably be easy but I’ll do it in C++ (new language yippee).
This one’s a pretty straightforward question, have a seen set containing all the elements seen so far and then just check each element against the seen set and return true if we find a duplicate and false otherwise.
Unfortunately, I have no idea how to implement sets in cpp so this was a learning experience:
set<type> is the type of set (need to #include <set>).insert(value) adds the value.erase(value) to remove the value.clear() to remove everything.size() to get the size.contains(value) to check if the value is in the setclass Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> seen {};
for (int num: nums) {
if (seen.contains(num)) {
return true;
}
seen.insert(num);
}
return false;
}
};
Time Complexity:
O(n)Space Complexity:
O(n)Time Taken:
4m 2s