0% found this document useful (0 votes)
12 views1 page

Neetcode 150 Cpp Sample Solution

The document presents a problem of detecting duplicates in an integer array. It outlines two approaches: a brute force method with O(n^2) time complexity and O(1) space complexity, and an optimal method using a hash set with O(n) time complexity and O(n) space complexity. Both methods return true if duplicates are found and false if all elements are distinct.

Uploaded by

sajjadansari0601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views1 page

Neetcode 150 Cpp Sample Solution

The document presents a problem of detecting duplicates in an integer array. It outlines two approaches: a brute force method with O(n^2) time complexity and O(1) space complexity, and an optimal method using a hash set with O(n) time complexity and O(n) space complexity. Both methods return true if duplicates are found and false if all elements are distinct.

Uploaded by

sajjadansari0601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Problem no 1- 217.

Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and
return false if every element is distinct.

Brute Force (C++):


🧠 Intuition: Compare every pair of elements to check for duplicates.

⏱ Time Complexity: O(n^2)

📦 Space Complexity: O(1)


bool containsDuplicate(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[i] == nums[j]) return true;
}
}
return false;
}

Optimal (C++):
🧠 Intuition: Use a hash set to keep track of seen elements. If any element is already in the set,
return true.

⏱ Time Complexity: O(n)

📦 Space Complexity: O(n)


bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int n : nums) {
if (seen.count(n)) return true;
seen.insert(n);
}
return false;
}

You might also like