Start learning free

LESSON 143 OF 344 · LOOPING OVER ARRAY INDICES

Linear Searching in JavaScript (O(n) Time Complexity)

Practice Read the full explanation

Given an array of integers nums, return the index of a given value.

If the value doesn't exist, return -1.

Example 1:

Input: nums = [1, 2, 4, 5], value = 4
Output: 2
Explanation: nums[2] is 4

Note:

Your algorithm should run in O(n) time and use O(1) space.


Hints:

We should try out each element in nums until we find one equal to value and return its index. How can we achieve this?

With a for loop, of course! We can use a variable num to iterate through the elements and an if statement to check if num == value:
for each num in nums:
	if num == value:
    # Solution found! But...

This is how we look for value in nums, but there's a problem. The problem asks us to return the index of that element, and by iterating like this we only know the value of the current element, not its index. How can we fix this?

We should use another method of iterating through an array: by indices! Let's use an index variable i to go through every index between 0 and nums.length - 1:
for i : 0 -> nums.length - 1:
	# index is i, value is nums[i]
  	if nums[i] == value:
    		return i
What if we don't have any element equal to value? Where should we return -1?

for i : 0 -> nums.length - 1:
	# index is i, value is nums[i]
  	if nums[i] == value:
    		return i

# Here:
return -1
If we reach the line with the comment, this means the for loop terminated naturally without returning any index. If we have had returned an index, we wouldn't even be executing this line of code as the program would have finished.

We have a for loop that performs exactly n iterations (where n is the length of nums), thus the Time Complexity is O(n).
The only extra space we use is the iterator variable i inside the loop, thus the Extra Space used is O(1).

Video Solution:

STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · LOOPING OVER ARRAY INDICES

    Linear Search in JavaScript, explained

    Understanding the Problem

    The core challenge of this problem is to find the index of a given value in an array. This is a fundamental problem in computer science known as linear search. Linear search is significant because it is the simplest search algorithm and is used in various applications where the dataset is small or unsorted.

    Potential pitfalls include not handling the case where the value is not present in the array, which should return -1.

    Approach

    To solve this problem, we can use a simple linear search algorithm. The idea is to iterate through each element in the array and check if it matches the given value. If a match is found, we return the index; otherwise, we return -1 after the loop completes.

    Let's discuss a naive solution and then optimize it:

    Naive Solution

    The naive solution involves iterating through the array using a for loop and checking each element. This approach is straightforward but not optimal for large datasets.

    Optimized Solution

    The optimized solution is essentially the same as the naive solution because linear search inherently has a time complexity of O(n). However, we can ensure that our implementation is clean and efficient.

    Algorithm

    Here is a step-by-step breakdown of the linear search algorithm:

    1. Initialize a loop to iterate through the array from index 0 to the last index.
    2. In each iteration, check if the current element is equal to the given value.
    3. If a match is found, return the current index.
    4. If the loop completes without finding a match, return -1.

    Code Implementation

    /**
     * Function to perform linear search on an array
     * @param {number[]} nums - The array of integers
     * @param {number} value - The value to search for
     * @return {number} - The index of the value if found, otherwise -1
     */
    function linearSearch(nums, value) {
      // Iterate through each element in the array
      for (let i = 0; i < nums.length; i++) {
        // Check if the current element is equal to the given value
        if (nums[i] === value) {
          // Return the current index if a match is found
          return i;
        }
      }
      // Return -1 if the value is not found in the array
      return -1;
    }
    
    // Example usage:
    const nums = [1, 2, 4, 5];
    const value = 4;
    console.log(linearSearch(nums, value)); // Output: 2
    

    Complexity Analysis

    The time complexity of the linear search algorithm is O(n) because we may need to check each element in the array in the worst case. The space complexity is O(1) because we are not using any additional space that scales with the input size.

    Edge Cases

    Potential edge cases include:

    • An empty array: The function should return -1.
    • The value is not present in the array: The function should return -1.
    • The value is present multiple times: The function should return the index of the first occurrence.

    Examples:

    // Edge case: empty array
    console.log(linearSearch([], 4)); // Output: -1
    
    // Edge case: value not present
    console.log(linearSearch([1, 2, 3], 4)); // Output: -1
    
    // Edge case: value present multiple times
    console.log(linearSearch([1, 2, 4, 4, 5], 4)); // Output: 2
    

    Testing

    To test the solution comprehensively, we should include a variety of test cases:

    • Simple cases with small arrays.
    • Edge cases as discussed above.
    • Large arrays to ensure performance.

    We can use JavaScript's built-in testing frameworks like Jest or Mocha for automated testing.

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to:

    • Understand the problem requirements and constraints.
    • Start with a simple, naive solution and then think about optimizations.
    • Consider edge cases and how your solution handles them.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Linear search is a fundamental algorithm that is easy to implement and understand. While it may not be the most efficient for large datasets, it is a valuable tool for small or unsorted arrays. Understanding and practicing such problems is crucial for developing strong problem-solving skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free