Tuesday, 11 June 2024

Find the index where x is present in the array using C++

 Problem Description:

Given an array of n elements and an integer x, find the index where x is present in the array. If there are multiple occurrences, find the leftmost one. If x is not present, return -1.


Input format: There are three lines of input. First line contains integer n. Second line contains n space separated integers representing the array. Third line contains the value of x. 

Output format: An integer representing the index of x in the array. 

Sample Input 1 5 1 3 4 2 1 1 

Sample Output 1 0 

Explanation 1 1 is present at 0 and 4 indexes and the leftmost index is 0. 

Constraints 1 <= n <= 100000 0 <= x <= 10^9


Solution:

Here is the solution to find the leftmost occurrence of an integer `x` in an array, written in C++:

#include <iostream>

#include <vector>

using namespace std;

int findLeftmostIndex(int n, const vector<int>& arr, int x) {
for (int i = 0; i < n; ++i) {
    if (arr[i] == x) {
        return i;
}
}
return -1;
}

int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; ++i) {
    cin >> arr[i];
}
int x;
cin >> x;
int result = findLeftmostIndex(n, arr, x);
cout << result << endl;
return 0;
}
//------------ End of Code----------------

### Explanation

1. **Input Handling**:

    - The integer `n` is read from the input, representing the number of elements in the array.

    - The array `arr` of size `n` is populated by reading `n` integers from the input.

    - The integer `x` is read from the input, representing the value to be searched in the array.


2. **Function `findLeftmostIndex`**:

    - This function takes the number of elements `n`, the array `arr`, and the integer `x` as parameters.

    - It iterates through the array using a `for` loop.

    - If it finds an element equal to `x`, it returns the current index.

    - If the loop completes without finding `x`, it returns `-1`.


### Edge Cases

- If `n` is 1, the function should correctly handle this minimal input size.

- If `x` is not in the array at all, the function should return `-1`.

- If `x` appears multiple times, the function should return the index of the first occurrence.


### Complexity

- **Time Complexity**: \(O(n)\), where \(n\) is the number of elements in the array. In the worst case, every element is inspected once.

- **Space Complexity**: \(O(1)\), as we are using a constant amount of extra space regardless of the input size.


This C++ program efficiently finds the leftmost occurrence of `x` in the array, meeting the problem's constraints and requirements.

No comments:

Post a Comment