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

  1. Iterate: Loop through array
  2. Check Condition: Compare element with criteria
  3. Track Results: Store index or increment counter
  4. 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.