Beginner Level

Implement the linearSearchIndex method that returns the first index of the target using linear search.

The input contains an integer array nums, its length size, and an integer target. Your task is to find the first index where target appears in the array.

Search the array from left to right. If the target is found, return its index. If the target does not exist in the array, return -1. For example, in [4,7,2,9], the target 2 is at index 2.

Example 1

Input
nums (int[]) = [4,7,2,9]
size (int) = 4
target (int) = 2
Returns (int) 2

Example 2

Input
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 4
Returns (int) -1

Example 3

Input
nums (int[]) = [8,8,9]
size (int) = 3
target (int) = 8
Returns (int) 0

Use linear search because the array does not need to be sorted.

Start from index 0 and compare each value with target. The first time both values are equal, return the current index. If the loop ends without finding the target, return -1.

Pseudocode:

function linearSearchIndex(nums, size, target):
    for i from 0 to size - 1:
        if nums[i] == target:
            return i
    return -1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.