InterviewSolution
Saved Bookmarks
| 1. |
Write a program for finding the first and last occurrences (or positions) of a number in an array of a sorted manner. |
|
Answer» Assign firstPos and lastPos values as -1 in the beginning, as we need to find them yet. Within for loop, you need to compare a given element with each element of an ARRAY. When an element is found for the first time, we will update the firstPos value with i. After that, WHENEVER we find an element, we will update the lastPos value with i. Then firstpos and lastPos value will be printed. // C++ PROGRAM#include <bits/stdc++.h>using namespace std;void findFirstAndLastFunc(int a[], int n, int x){ int firstPos = -1, lastPos = -1; for (int i = 0; i < n; i++) { if (x != a[i]) continue; if (firstPos == -1) firstPos = i; lastPos = i; } if (firstPos != -1) COUT << "First Occurrence = " << firstPos<< "\n Last Occurrence = " << lastPos; else cout << "Element not Found";}int main(){ int a[] = { 1, 2, 2, 2, 3, 3, 4, 5, 7, 7}; int n = sizeof(a) / sizeof(int); int x = 7; findFirstAndLastFunc(a, n, x); return 0;}Output: First Occurrence = 8Last Occurrence = 9 |
|