18

Phase 4 - Level 4: Aggregation & Comparison

Chapter 18 • Intermediate

90 min

Phase 4 - Level 4: Aggregation & Comparison

Introduction

Learn to compare arrays, merge them, find common elements, and perform aggregate operations across multiple arrays.

Key Concepts

Array Comparison

  • Same Order: Compare element by element
  • Ignore Order: Check if arrays contain same elements
  • Subset Check: Are all elements of one in other?

Array Merging

  • Concatenate: Combine two arrays
  • Merge Sorted: Combine sorted arrays maintaining order
  • Union: All unique elements from both
  • Intersection: Common elements

Aggregate Operations

  • Element-wise Sum: Add corresponding elements
  • Element-wise Product: Multiply corresponding elements
  • Frequency Analysis: Count occurrences of each element

Common Patterns

Compare Arrays (Same Order)

python.js
if len(arr1) != len(arr2):
    return False
for i in range(len(arr1)):
    if arr1[i] != arr2[i]:
        return False
return True

Find Common Elements

python.js
common = []
for element in arr1:
    if element in arr2 and element not in common:
        common.append(element)

Merge Arrays

python.js
merged = arr1 + arr2

Problem-Solving Approach

  1. Determine Operation: Compare, merge, or aggregate?
  2. Handle Sizes: What if arrays have different lengths?
  3. Avoid Duplicates: Use conditions or sets
  4. Maintain Order: Preserve original order if needed

Hands-on Examples

Compare Arrays

# Take two arrays
n1 = int(input("Enter size of first array: "))
arr1 = []
for i in range(n1):
    arr1.append(int(input(f"Array1 element {i+1}: ")))

n2 = int(input("Enter size of second array: "))
arr2 = []
for i in range(n2):
    arr2.append(int(input(f"Array2 element {i+1}: ")))

# Compare arrays
if len(arr1) != len(arr2):
    print("Arrays are not equal (different sizes)")
else:
    equal = True
    for i in range(len(arr1)):
        if arr1[i] != arr2[i]:
            equal = False
            break
    
    if equal:
        print("Arrays are equal")
    else:
        print("Arrays are not equal")

First check if lengths match. Then compare element by element. If any mismatch, arrays are not equal.