16
Phase 4 - Level 2: Searching & Counting Logic
Chapter 16 • Intermediate
75 min
Phase 4 - Level 2: Searching & Counting Logic
Introduction
Learn to search for elements in arrays and count occurrences. This level covers linear search, counting patterns, and finding elements with specific properties.
Key Concepts
Searching Operations
- Linear Search: Check each element sequentially
- First Occurrence: Find first index of element
- Last Occurrence: Find last index of element
- Existence Check: Determine if element exists
Counting Operations
- Count occurrences of specific value
- Count elements meeting criteria
- Count unique elements
- Count elements in ranges
Common Patterns
Linear Search
python.js
for i in range(len(arr)):
if arr[i] == target:
return i
Count Occurrences
python.js
count = 0
for element in arr:
if element == target:
count += 1
Problem-Solving Approach
- Iterate: Loop through array
- Check Condition: Compare element with criteria
- Track Results: Store index or increment counter
- Handle Edge Cases: Empty array, not found
Common Operations
- Find Element: Return index or -1 if not found
- Count Matches: How many elements meet condition?
- First/Last: Track first or last occurrence
- Uniqueness: Check if all elements are unique
Hands-on Examples
Linear Search in Array
# Take array and target
n = int(input("Enter array size: "))
arr = []
for i in range(n):
arr.append(int(input(f"Enter element {i+1}: ")))
target = int(input("Enter element to search: "))
# Linear search
found = False
index = -1
for i in range(len(arr)):
if arr[i] == target:
found = True
index = i
break
if found:
print(f"Element found at index {index}")
else:
print("Element not found")Iterate through array, compare each element with target. If found, store index and break. If loop completes, element not found.
Related Tutorials
🔗Related Content
- 💻
Phase 4 - Practice Problems
Practice Phase 4 concepts with hands-on coding problems
- 📝
Phase 4 - Quiz
Test your Phase 4 understanding with assessment questions
- ➡️
Phase 5 - Get Started
Continue to Phase 5 after mastering Phase 4
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum