Pages

Friday, April 11, 2025

Check duplicate numbers return 1 if true, return 0 if false in C++ (Array Assignment) - Full Explaination

 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: For cin, cout.

  • vector: A dynamic array that grows/shrinks.

  • algorithm: Contains sort() function.


🟦 Function Header:

bool containsDuplicate(vector<int> nums)
  • This function takes a copy of a vector of integers.

  • It returns a booltrue 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] and nums[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

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...