#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Searching Algorithms

Linear Search with Duplicates

Linear Search scans an array sequentially, comparing each element with the target value. When an array contains duplicate values, a simple linear search that returns on the first match may not be enough — often we need all indices where the value occurs.

Algorithm Steps

  • Start from the first index of the array.
  • Compare the current element with the target value.
  • If it matches, record the index (instead of stopping).
  • Continue until the end of the array is reached.
  • Return the list of all matching indices.
def linear_search_all(arr, target):
    indices = []
    for i, value in enumerate(arr):
        if value == target:
            indices.append(i)
    return indices

print(linear_search_all([4, 2, 7, 2, 9, 2], 2))  # Output: [1, 3, 5]

Complexity

CaseTimeSpace
BestO(1)O(1)
Worst (search all)O(n)O(k) for k matches

When to Use

  • Unsorted arrays where binary search cannot be applied.
  • Small datasets where the overhead of sorting is not worthwhile.
  • Situations that require every occurrence of a value, not just existence.

Tracing the Algorithm on a Small Array

Take the array [5, 3, 5, 1, 5] and the target 5. Walking through it by hand shows exactly why the loop must not stop early.

IndexValueMatch?Indices so far
05Yes[0]
13No[0]
25Yes[0, 2]
31No[0, 2]
45Yes[0, 2, 4]

If the target never appears, the function simply returns an empty list. Callers can test the result with if not result:, which reads naturally and avoids a separate "found" flag.

Every element is visited once, so the time is always proportional to the array length when you need all positions, even if the first element already matches.

Useful Variations of the Same Idea

Real problems rarely ask for exactly "all indices". Small changes to the loop answer related questions without extra passes.

def first_and_last(arr, target):
    first = last = -1
    for i, v in enumerate(arr):
        if v == target:
            if first == -1:
                first = i
            last = i
    return first, last

def count_occurrences(arr, target):
    return sum(1 for v in arr if v == target)

def last_index(arr, target):
    for i in range(len(arr) - 1, -1, -1):   # scan from the end
        if arr[i] == target:
            return i
    return -1

print(first_and_last([5, 3, 5, 1, 5], 5))   # (0, 4)
print(count_occurrences([5, 3, 5, 1, 5], 5))  # 3

Scanning from the end is a neat trick when only the last occurrence matters, because the loop can return as soon as it finds a match.

For very large inputs you may not want to build the whole list in memory at once. Turning the function into a generator with yield i lets the caller process each position as soon as it is found, and stop whenever it has seen enough.

When Another Approach Is Better

Linear search is simple, but it is not always the right tool.

  • Sorted array: use binary search twice (lower bound and upper bound). The duplicates sit in one block, so you find its start and end in logarithmic time.
  • Many queries on the same data: build a dictionary that maps each value to its list of indices once. After that single pass, every lookup is close to constant time.
  • One-off query on unsorted data: plain linear search wins, because sorting or indexing would cost more than the search itself.
from collections import defaultdict

positions = defaultdict(list)
for i, v in enumerate([4, 2, 7, 2, 9, 2]):
    positions[v].append(i)
print(positions[2])   # [1, 3, 5]

Common Mistakes

  • Putting return inside the if, which stops at the first match.
  • Returning -1 for "not found" in one function and an empty list in another; pick one convention and document it.
  • Comparing floating-point values with ==; use a tolerance when the data comes from calculations.
  • Forgetting that the result list itself uses extra space proportional to the number of matches.