Last Updated: 2 Aug, 2021

Linear Search

Easy
Asked in company
Capegemini Consulting India Private Limited

Problem statement

You are given an array/list ‘ARR’ of ‘N’ positive integers’ and an integer ’X’. Your task is to find out the first instance of X in the array. If no such instance exists, return -1.

Note:

Consider 0-based indexing of the array.
For Example :
Input : arr[] = {5, 1, 3, 4, 3}, X = 3
Output : 2
There are two instances of 3 in the array -  2 and 4. Since we need to return the first instance our result is 2.
Input Format :
The first line contains a single integer ‘T’ representing the number of test cases.Then ‘T’ test cases follow.

The first line of each test case contains the integer ‘N’ and ‘X’ representing the size of the input ‘ARR’ and the integer to be searched.

The next line of each test case contains ‘N’ single space-separated integers that represent the elements of the ‘ARR’.
Output Format :
For each test case, return the leftmost occurrence of integer X or -1.
Note:
You don’t need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 10^5
0 <= ARR[i] <= 10^9

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • We traverse the array from left to right.
  • If X is found at any index, say i,  return i immediately.
  • If at the end of traversal no index i is found return -1.