That's the spirit, Debadatta! π₯ Let's break down your teacher's code step-by-step and understand everything clearly, like a pro. πͺ
✅ Full Teacher’s Code First:
#include <iostream>
#include <vector>
#include <algorithm> // for sort
using namespace std;
// Function to check for duplicates
bool containsDuplicate(vector<int> nums) {
sort(nums.begin(), nums.end()); // Step 1: Sort the array
for (int i = 1; i < nums.size(); i++) { // Step 2: Check adjacent elements
if (nums[i - 1] == nums[i]) {
return true; // Duplicate found
}
}
return false; // No duplicates found
}
int main() {
vector<int> numbers = {1, 1, 2, 3, 4, 5}; // Sample input
if (containsDuplicate(numbers)) {
cout << "Duplicate found" << endl;
} else {
cout << "No duplicates" << endl;
}
return 0;
}
π§ Step-by-step Breakdown:
π© #include
and setup:
#include <iostream>
#include <vector>
#include <algorithm>
-
iostream
: Forcin
,cout
. -
vector
: A dynamic array that grows/shrinks. -
algorithm
: Containssort()
function.
π¦ Function Header:
bool containsDuplicate(vector<int> nums)
-
This function takes a copy of a vector of integers.
-
It returns a
bool
—true
if a duplicate is found,false
otherwise.
π¨ Step 1: Sort the array
sort(nums.begin(), nums.end());
-
Sorting makes it easy to compare each number with its neighbor.
-
After sorting:
{1, 1, 2, 3, 4, 5}
π§ Step 2: Check each pair
for (int i = 1; i < nums.size(); i++) {
if (nums[i - 1] == nums[i]) {
return true;
}
}
-
Start from index 1 (second element)
-
Compare
nums[i - 1]
andnums[i]
-
If they are equal, it means a duplicate exists.
π₯ Step 3: No duplicates? Return false
return false;
-
If loop finishes and no duplicate is found, return
false
.
π¦ main()
Function:
int main() {
vector<int> numbers = {1, 1, 2, 3, 4, 5};
if (containsDuplicate(numbers)) {
cout << "Duplicate found" << endl;
} else {
cout << "No duplicates" << endl;
}
return 0;
}
-
Create a vector
numbers
-
Call the function
containsDuplicate(numbers)
-
Print message based on the result
π Example Runs:
Input | Output |
---|---|
{1, 1, 2, 3} |
Duplicate found |
{1, 2, 3, 4} |
No duplicates |
{9, 8, 9, 7} |
Duplicate found |
π Summary of Logic:
Step | What it does |
---|---|
1 | Sort the array |
2 | Loop through it |
3 | Compare each number to its previous one |
4 | If equal → duplicate found |
5 | Else → return false |
No comments:
Post a Comment