Chapter 3DSA (Data Structures & Algorithms)~1 min read
Arrays
सर्वात Basic Data Structure
Array हे सर्वात fundamental data structure आहे. Contiguous memory मध्ये elements store होतात. Index ने O(1) मध्ये access करता येतो. Majority of DSA problems arrays वर आधारित असतात.
Array basics
python
# Python मध्ये list = dynamic array
arr = [5, 2, 8, 1, 9, 3]
# Access — O(1)
print(arr[0]) # 5
print(arr[-1]) # 3 (last element)
# Insert at end — O(1)
arr.append(7)
# Insert at index — O(n)
arr.insert(2, 99)
# Delete — O(n)
arr.remove(8) # value ने
arr.pop(0) # index ने
# Length
print(len(arr))Two Pointer Technique
Two Sum — sorted array (Two Pointers)
python
# Problem: sorted array मध्ये दोन numbers शोधा जे target ला add होतात
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1 # sum वाढवायला left पुढे
else:
right -= 1 # sum कमी करायला right मागे
return []
arr = [1, 3, 5, 7, 9, 11]
print(two_sum_sorted(arr, 12)) # [1, 4] → 3+9=12Sliding Window — Max sum subarray
python
# Problem: k size च्या subarray चा maximum sum
def max_subarray_sum(arr, k):
window_sum = sum(arr[:k]) # पहिली window
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k] # window slide
max_sum = max(max_sum, window_sum)
return max_sum
arr = [2, 1, 5, 1, 3, 2]
print(max_subarray_sum(arr, 3)) # 9 (5+1+3)✅ Key Points — लक्षात ठेवा
- ▸Array access O(1), insert/delete O(n)
- ▸Two Pointers — sorted array problems
- ▸Sliding Window — subarray/substring problems
- ▸Python list = dynamic array (ArrayList)
- ▸Index out of bounds — common bug
0/10 chapters पूर्ण