Given an array of integers nums and an integer target, find the smallest index (0 based indexing) where the target appears in the array. If the target is not found in the array, return -1
Input: nums = [2, 3, 4, 5, 3], target = 3
Output: 1
Explanation: The first occurence of 3 in nums is at index 1
Input: nums = [2, -4, 4, 0, 10], target = 6
Output: -1
Explanation: The value 6 does not occur in the array, hence output is -1
Input: nums = [1, 3, 5, -4, 1], target = 1
Let's break the problem statement into an example to understand it better. Imagine having a long shelf filled with books, and each book has a unique number written on its spine. The ask is to look for the first book with a specific number, let's say 2.
To achieve this we will simply start scanning each book and once a book with number 2 is got, stop the scan procedure.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Linear Search Function
int linearSearch(vector<int>& nums, int target) {
// Traverse the entire vector
for (int i = 0; i < nums.size(); i++) {
// Check if current element is target
if (nums[i] == target) {
// Return index
return i;
}
}
// If target not found
return -1;
}
};
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
int target = 4;
// Create an instance of the Solution class
Solution sol;
// Call the linearSearch method
int result = sol.linearSearch(nums, target);
// Print the result
cout << result << endl;
return 0;
}
import java.util.*;
class Solution {
// Linear Search Function
public int linearSearch(int[] nums, int target) {
// Traverse the entire array
for (int i = 0; i < nums.length; i++) {
// Check if current element is target
if (nums[i] == target) {
// Return if target found
return i;
}
}
// If target not found
return -1;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
int target = 4;
// Create an instance of the Solution class
Solution sol = new Solution();
// Call the linearSearch method
int result = sol.linearSearch(nums, target);
System.out.println(result);
}
}
from typing import List
class Solution:
# Linear Search Function
def linearSearch(self, nums: List[int], target: int) -> int:
# Traverse the entire array
for i in range(len(nums)):
# Check if current element is target
if nums[i] == target:
# Return index if target found
return i
# If target not found
return -1
# Main function
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5]
target = 4
# Create an instance of the Solution class
sol = Solution()
# Call the linearSearch method and store the result
result = sol.linearSearch(nums, target)
print(result)
class Solution {
linearSearch(nums, target) {
// Traverse the entire array
for (let i = 0; i < nums.length; i++) {
// Check if current element is target
if (nums[i] === target) {
// Return if found
return i;
}
}
// If the target is not found
return -1;
}
}
const nums = [1, 2, 3, 4, 5];
const target = 4;
// Create an instance of the Solution class
const sol = new Solution();
// Call the linearSearch method and store the result
const result = sol.linearSearch(nums, target);
console.log(result);
Q: What happens if the target is not found in the array?
A: If the target is not present, the function should return -1. This indicates that no index contains the target value. Example: Input: nums = [1, 2, 3, 4], target = 5 Output: -1
Q: Is linear search suitable for very large arrays?
A: Linear search is not ideal for large datasets because of its O(n) time complexity. For unsorted arrays, it's often the only choice. However, for sorted arrays, use binary search O(logn)) to improve efficiency. Alternatively, hash-based methods O(1) average case) can be used if the data structure supports it.
Q: How would you modify the function to return all indices of the target instead of just the smallest?
A: To return all indices: Traverse the array completely, even after finding the first occurrence. Use a list to store indices of all occurrences of the target. Example: Input: nums = [1, 2, 3, 2, 4], target = 2 Output: [1, 3]
Q: How can linear search be optimized for specific scenarios?
A: Linear search can be optimized for: If a specific target appears frequently, keep track of its last found index to start the search from there in subsequent searches. If the array is partially sorted or has a specific pattern, consider stopping early when certain conditions are met.