This is an open source platform.
Create coding videos, upload them on YouTube, and help the community grow.
Teaching is the fastest way to learn β and the best way to never forget
what you know π
β‘ Start Recording
Screen only
Screen With Camera
β‘Start Recording
β
Selected Template
${temp1}
Screen only
Screen With Camera
Start Recording
β
β‘ Show Preview
Thumbnail Templates
Generating Thumbnail...
Master In-Demand Tech. Get Paid
Linear Search
Given an array of integers nums and a target value, return the index of the target if found, otherwise return -1.
Difficulty:
JavaScript Solution
function linearSearch(nums, target) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) return i;
}
return -1;
}
Explanation: We scan the array sequentially until the target is found.
β± O(n) | πΎ O(1)
Java Solution
class Solution {
public int linearSearch(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) return i;
}
return -1;
}
}
Explanation: Each element is checked one by one.
β± O(n) | πΎ O(1)
Python Solution
def linear_search(nums, target):
for i, val in enumerate(nums):
if val == target:
return i
return -1
Explanation: We iterate through the list until the target value is found.