Find the Second Occurrence of the Element

Get an array of Integers arr[] with size n and element e to be found. Apply Linear Search / Binary Search to find the element e’s second occurrence position in the array arr[]. If element e is found, print its second occurred index; if not found or occurred less than 2 times, print -1.

Examples

Input 1:

5

5 7 9 3 9

9

Output 1:

4

Input 2:

5

5 7 9 3 1

4

Output 2:

-1

Input 3:

5

5 7 9 3 1

9

Output 3:

-1

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
				
					

import java.util.*;

class SearchSO

{

public static void main(String args[])

    {


//Variable and  Object Declarations

        Scanner input = new Scanner(System.in);

int n,e,pos=-1,count=0;

//Getting size of Array & Declare Array arr[]

n = input.nextInt();

int arr[] = new int[n];


//Get n values to array arr[]

for(int i = 0; i<n; i++)

{

arr[i] = input.nextInt();

}


e = input.nextInt();


//Linear Search

for(int i = 0; i<n; i++)

{

if(arr[i]==e)

{

pos = i;

count++;

if(count == 2)

{

break;

}

}

}

if(count<2)

{

System.out.println(-1);

}

else

{

System.out.print(pos);

}

      }

}

Program Explanation

Comments