Last Updated: 9 Mar, 2021

First index of element

Easy
Asked in company
EPAM Systems

Problem statement

Take an array with n elements with possibly duplicate elements as the input. The task is to find the index of the first occurrences of the element x in the array and, if it is not present, return -1.

Input Format:

The first line contains an integer N representing the size of the array.

The next line contains N space-separated integers representing the elements of the array.

The last line contains an integer 'x' whose index has to be found.

Output Format:

The only line of the output prints the Index or -1.
Constraints:
1 <= N <= 10^3
1 <= arr[i] <= 10^9
1 <= x < N

Approaches

01 Approach

  • We create a variable ‘first’ with value -1 to store the answer.
  • We iterate the array forward and update the value of first if an occurrence of x is found. We break out of this loop.
  • Finally, print the value of first.