Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print uncommon elements from two sorted arrays
Given two sorted arrays, we need to find and print all uncommon elements (elements that appear in one array but not in both). This problem uses a two-pointer technique to efficiently traverse both arrays simultaneously.
Given : array1[] = {1, 4, 6, 9, 12}
array2[] = {2, 4, 7, 8, 9, 10}
Output : 1 2 6 7 8 10 12
Syntax
void printUncommonElements(int arr1[], int n1, int arr2[], int n2);
Algorithm
- Initialize two pointers
iandjto traverse both arrays - Compare elements at current positions:
- If
arr1[i] < arr2[j]: printarr1[i]and incrementi - If
arr1[i] > arr2[j]: printarr2[j]and incrementj - If
arr1[i] == arr2[j]: increment bothiandj(common element, skip)
- If
- Print remaining elements from both arrays
Example
#include <stdio.h>
void printUncommonElements(int arr1[], int n1, int arr2[], int n2) {
int i = 0, j = 0;
printf("Uncommon elements: ");
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
printf("%d ", arr1[i]);
i++;
}
else if (arr1[i] > arr2[j]) {
printf("%d ", arr2[j]);
j++;
}
else {
/* Equal elements - skip both */
i++;
j++;
}
}
/* Print remaining elements from arr1 */
while (i < n1) {
printf("%d ", arr1[i]);
i++;
}
/* Print remaining elements from arr2 */
while (j < n2) {
printf("%d ", arr2[j]);
j++;
}
printf("<br>");
}
int main() {
int array1[] = {1, 4, 6, 9, 12};
int array2[] = {2, 4, 7, 8, 9, 10};
int n1 = sizeof(array1) / sizeof(array1[0]);
int n2 = sizeof(array2) / sizeof(array2[0]);
printf("Array 1: ");
for (int i = 0; i < n1; i++) {
printf("%d ", array1[i]);
}
printf("<br>");
printf("Array 2: ");
for (int i = 0; i < n2; i++) {
printf("%d ", array2[i]);
}
printf("<br>");
printUncommonElements(array1, n1, array2, n2);
return 0;
}
Array 1: 1 4 6 9 12 Array 2: 2 4 7 8 9 10 Uncommon elements: 1 2 6 7 8 10 12
How It Works
The algorithm compares elements from both arrays using two pointers:
- Elements 1 vs 2: 1 < 2, so print 1 and move to next element in array1
- Elements 4 vs 2: 4 > 2, so print 2 and move to next element in array2
- Elements 4 vs 4: Equal elements, skip both (common element)
- Continue until one array is exhausted
- Print remaining elements from the other array
Key Points
- Time Complexity: O(n1 + n2) where n1 and n2 are array sizes
- Space Complexity: O(1) as no extra space is used
- Works only with sorted arrays
- Preserves the sorted order in output
Conclusion
This two-pointer approach efficiently finds uncommon elements from two sorted arrays in linear time. The algorithm leverages the sorted property to avoid nested loops and maintain optimal performance.
Advertisements
