📘 Introduction to Arrays
🧠 What is an Array?
An array is a linear data structure that stores a fixed-size sequence of elements of the same type in contiguous memory locations. Arrays allow efficient random access via indexing and are foundational in many algorithmic solutions.
🛠️ Array Basics
✅ Declaration and Initialization
arr = [10, 20, 30, 40]
✅ Accessing Elements
print(arr[0]) # Output: 10
✅ Updating Elements
arr[2] = 99
⚙️ Basic Array Operations
Operation | Time Complexity |
---|---|
Access by index | \(O(1)\) |
Update by index | \(O(1)\) |
Insert at end | \(O(1)\) (amortized for dynamic arrays) |
Insert at index | \(O(n)\) |
Delete by index | \(O(n)\) |
Search (linear) | \(O(n)\) |
🔍 Understanding Memory Layout
Arrays are stored in contiguous blocks in memory, enabling constant-time access using the index:
arr[3] → Base Address + 3 × Size_of_Element
👉 This is why arrays are faster than linked lists for indexed access.
📊 Types of Arrays
- 1D Array: Single row of elements — arr[5]
- 2D Array: Matrix/grid — matrix[3][3]
- Multidimensional Arrays: Arrays within arrays
🧪 Example Problems
🔹 Problem 1: Find Maximum Element in an Array
arr = [2, 5, 1, 9, 3]
max_val = arr[0]
for num in arr:
if num > max_val:
max_val = num
print(max_val)
🔹 Problem 2: Reverse an Array In-Place
arr = [1, 2, 3, 4, 5]
start = 0
end = len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
print(arr)
✍️ Practice Assignments
-
Write a program to calculate the sum and average of elements in an array.
-
Find the second largest element in an array.
-
Implement a program to remove all negative numbers from an array.
-
Practice accessing and updating values in a 2D array.
🔔 Next : We’ll dive into array problem-solving patterns like prefix sums, two-pointer technique, and sliding window.