Hone logo
Hone
Problems

Implement Linear Scan for Finding Elements in Go

This challenge focuses on implementing a fundamental search algorithm: linear scan. You will create a Go function that iterates through a collection of elements one by one to find a specific target value. This technique is a building block for understanding more complex search algorithms and is commonly used in scenarios where the data is unsorted or small.

Problem Description

Your task is to implement a function in Go called LinearScan that takes two arguments:

  1. A slice of integers (data).
  2. An integer to search for (target).

The function should traverse the data slice from the beginning to the end. If the target value is found within the slice, the function should return the index of the first occurrence of the target. If the target value is not present in the slice, the function should return -1.

Key Requirements:

  • The function must iterate through the slice sequentially (from index 0 upwards).
  • It should return the index of the first match.
  • If no match is found, return -1.

Expected Behavior:

  • For a non-empty slice containing the target, return its index.
  • For a non-empty slice not containing the target, return -1.
  • For an empty slice, return -1.

Edge Cases to Consider:

  • An empty input slice.
  • A slice where the target appears multiple times (ensure the first occurrence is returned).
  • A slice where the target is the first or last element.

Examples

Example 1:

Input: data = [10, 5, 15, 20, 5], target = 5
Output: 1
Explanation: The target value 5 is found at index 1. Although 5 also appears at index 4, we return the index of the first occurrence.

Example 2:

Input: data = [1, 2, 3, 4, 5], target = 6
Output: -1
Explanation: The target value 6 is not present in the slice.

Example 3:

Input: data = [], target = 10
Output: -1
Explanation: The input slice is empty, so the target cannot be found.

Example 4:

Input: data = [7], target = 7
Output: 0
Explanation: The target value 7 is found at the first and only index, 0.

Constraints

  • The input slice data will contain between 0 and 10,000 integers, inclusive.
  • The integers in data and the target value will be between -1,000,000 and 1,000,000, inclusive.
  • The implementation should complete within a reasonable time for the given constraints, implying an O(n) time complexity is acceptable and expected.

Notes

  • This exercise is about implementing the algorithm itself, not about optimizing for speed beyond the inherent efficiency of linear scan for an unsorted array.
  • Consider how you would handle the case of an empty input slice gracefully.
  • The goal is to find the first occurrence. This means as soon as you find a match, you can stop searching and return its index.
Loading editor...
go