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 the last occurrence of elements in array in relative order in C Program.
Given an array with elements and the task is to print the last occurrences of the given elements in the list. Here we not only have to remove the duplicate elements but also we have to maintain the order of the occurrences of the elements in an array as per the last time they have occurred.
For example, if we have an array of 6 elements containing some duplicate values i.e., {1, 3, 2, 3, 1, 2}, the result should be in the form of 3 1 2.
Syntax
void printLastOccurrence(int arr[], int n);
Algorithm
- Create an array to store the last index of each element
- Iterate through the array and store the last occurrence index for each element
- Traverse the original array again and print elements only when their current index matches their last occurrence index
Example
#include <stdio.h>
void printLastOccurrence(int arr[], int n) {
int lastIndex[1000] = {-1}; /* Assuming elements are small positive integers */
int i;
/* Initialize all indices to -1 */
for (i = 0; i < 1000; i++) {
lastIndex[i] = -1;
}
/* Store the last occurrence index of each element */
for (i = 0; i < n; i++) {
lastIndex[arr[i]] = i;
}
/* Print elements only at their last occurrence */
for (i = 0; i < n; i++) {
if (lastIndex[arr[i]] == i) {
printf("%d ", arr[i]);
}
}
printf("<br>");
}
int main() {
int arr[] = {4, 2, 2, 4, 1, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
printf("Last occurrences: ");
printLastOccurrence(arr, n);
return 0;
}
Original array: 4 2 2 4 1 5 1 Last occurrences: 2 4 5 1
How It Works
- Store Last Index: We iterate through the array and for each element, we store its current index. This automatically overwrites previous indices, keeping only the last one.
- Check and Print: We traverse the array again and print an element only when its current position matches the stored last index.
- Maintain Order: Since we traverse the original array sequentially, the relative order is preserved.
Time and Space Complexity
| Aspect | Complexity | Description |
|---|---|---|
| Time Complexity | O(n) | Two passes through the array |
| Space Complexity | O(k) | Where k is the range of input elements |
Conclusion
This algorithm efficiently finds and prints the last occurrence of each element while maintaining their relative order. It uses a simple array-based approach suitable for small positive integers.
Advertisements
