DSA — Arrays
What is an Array?
A collection of elements stored at contiguous memory locations.
# Creating arrays
arr = [1, 2, 3, 4, 5]
arr = list(range(10))
Array Operations
| Operation | Time Complexity |
|---|---|
| Access | O(1) |
| Search | O(n) |
| Insert | O(n) |
| Delete | O(n) |
Basic Operations
# Access
first = arr[0]
last = arr[-1]
# Insert
arr.append(6)
arr.insert(0, 0)
# Delete
arr.remove(3)
popped = arr.pop()
# Search
index = arr.index(4)
exists = 4 in arr
# Sort
arr.sort()
arr.sort(reverse=True)
Array Traversal
# For loop
for i in range(len(arr)):
print(arr[i])
# For each
for item in arr:
print(item)
# Enumerate
for i, item in enumerate(arr):
print(f"Index {i}: {item}")
Common Array Problems
# Find maximum
def find_max(arr):
max_val = arr[0]
for num in arr:
if num > max_val:
max_val = num
return max_val
# Reverse array
def reverse_array(arr):
return arr[::-1]
# Remove duplicates
def remove_duplicates(arr):
return list(set(arr))
Mini Practice
- Create and manipulate arrays
- Implement array search
- Find maximum and minimum
- Reverse an array
Up Next
Continue with Strings — string manipulation.
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in DSA?
Arrays is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in DSA?
Arrays is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.