Linear Search — Practice Problems in Data structures & algorithms (DSA)
Practice Sheet: Applying Linear Search to common array problems
Goal: Learn how
to scan an array from left to right and apply Linear Search to find a first
index, check presence, count occurrences, find all indexes, and find a maximum
value.
Problem 1 — Find First Index
Given the array [15, 8, 22, 10, 7, 22] and target 22.
• Return
the first index of 22.
• Expected
answer: 2
Problem 2 — Check Presence
Given the array [4, 9, 12, 6, 18, 3] and target 15.
• Return
True if 15 is present.
• Return
False if 15 is not present.
• Expected
answer: False
Problem 3 — Count Occurrences
Given the array [5, 2, 5, 8, 5, 9, 2] and target 5.
• Return
the number of occurrences of 5.
• Expected
answer: 3
Problem 4 — Find All Indexes
Given the array [3, 7, 3, 10, 3, 5, 3] and target 3.
• Return
all indexes where 3 occurs.
• Expected
answer: [0, 2, 4, 6]
Problem 5 — Find Maximum
Given the array [12, 45, 7, 89, 23, 56].
• Use
the Linear Search approach to find the maximum element.
• Return
the maximum element.
• Expected
answer: 89
How to
Practice These Problems
Use the same simple process for each problem:
|
Step |
What to do |
|
1.
Understand |
Identify
the array and the target/requirement. |
|
2. Apply Linear Search |
Check
elements from left to right. |
|
3. Record the result |
Depending
on the question, save the first index, True/False, count, all indexes, or
maximum. |
|
4.
Code it |
Write
the solution yourself in Python. |
|
5. Check complexity |
For a
basic Linear Search solution, time is generally O(n); extra space is
generally O(1), except when the task requires storing multiple
indexes/results. |
Important: If
the question asks only whether an element is present, you can stop when the
first match is found. If it asks for the count or all indexes, you must
continue checking the whole array.
Answer:
from array import*
arr=array('i',[12,5,8,20,15,7])
for x in arr:
if x==20:
print("yes 20 present in array",arr.index(20))
break
else:
print("not present")
arr1=array('i', [15,8,22,10,7,22])
print("The first index of 22 is",arr1.index(22))
arr2=array('i',[4,9,12,6,18,3])
for i in range(len(arr2)):
if i==15:
print("if present")
else:print("if not present")
arr3=array('i',[5,2,5,8,5,9,2,5,5])
print("The number of occurrence of 5 is",arr3.count(5))
count=0
for co in arr3:
if co==5:
count=count+1
print("the number of occurnce of 5 is",count)
arr4=array('i',[3,7,3,10,3,5,3])
count=0
a=[]
for index,co in enumerate(arr4):
if co==3:
count=count+1
a.append(index)
print("the number of occurnce of 3 is",count)
print("index of 3 is",a)
arr5=array('i',[12,45,7,89,23,56])
print(max(arr5))
print(sorted(arr5)[len(sorted(arr5))-1])
Comments
Post a Comment