05
SepLinear Search with Duplicates
Linear Search with Duplicates
The Linear Search Algorithm is a simple search algorithm that sequentially checks each element in an array until a match is found or the array is fully traversed. When handling duplicates, the algorithm is modified to return all indices where the target value appears, rather than stopping at the first match. This approach is useful for unsorted arrays or when all occurrences of a value are needed. The time complexity is O(n), where n is the length of the array.
Example
- Input: nums = [5, 2, 8, 5, 1, 5, 3], target = 5
- Output: [0, 3, 5]
- Explanation: The target value 5 appears at indices 0, 3, and 5 in the array.
Logic
Enter an array of numbers (comma-separated) and a target value to find all indices where the target appears using the Linear Search algorithm.
Program (Python - Linear Search with Duplicates)
The following Python code implements the Linear Search algorithm to find all indices of a target value in an array, with O(n) time complexity, where n is the length of the array.
def linearSearchDuplicates(nums, target):
result = []
for i in range(len(nums)):
if nums[i] == target:
result.append(i)
return result
# Example usage
nums = [5, 2, 8, 5, 1, 5, 3]
target = 5
print(linearSearchDuplicates(nums, target)) # Output: [0, 3, 5]
Output
For the input nums = [5, 2, 8, 5, 1, 5, 3] and target = 5, the output is:
[0, 3, 5]
Explanation:
The target value 5 is found at indices 0, 3, and 5 in the array.
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.