Problem Statement: Given an array of integers. Your task is to write a C program to find and display the duplicate elements present in the array.
Example:
Input: arr[] = {3, 2, 4, 2, 7, 8, 4, 1, 8} Output: Duplicate numbers: 2 4 8 Input: arr[] = {1, 4, 1, 3, 2} Output: Duplicate numbers: 1
Algorithm to Find Duplicate Elements.
Below are the steps that you need to follow:
Step 1: Traverse through the array one element at a time.
Step 2: For each element, check if it appears again later in the array.
Step 3: If the element is found later in the array and is not already marked as a duplicate, mark it as a duplicate and print it.
Step 4: Continue this process for each element.
Below is the C program implementation to find and display duplicate numbers from the given array.
C code:
//C program to find duplicate number from the given array #include <stdio.h> int main() { int arr[] = {3, 2, 4, 2, 7, 8, 4, 1, 8}; int size = sizeof(arr) / sizeof(arr[0]); printf("Duplicate elements: "); //traverse to find duplicate for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { if (arr[i] == arr[j]) { printf("%d ", arr[i]); break; } } } printf("\n"); return 0; }
Duplicate elements: 2 4 8
Time Complexity: The time complexity of this algorithm is O(n^2) in the worst case, where n is the number of elements in the array.
Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variables and other variables.
Related Articles:
No comments:
Post a Comment