Merge Two Sorted Arrays in Python

🚀 Day 10 of DSA Practice: Merge Two Sorted Arrays Today’s problem is a classic and super important for interviews 👇 🧩 Problem Given two sorted arrays, merge them into a single sorted array. 🔍 Example Input: Array 1: [1, 3, 5] Array 2: [2, 4, 6] Output: [1, 2, 3, 4, 5, 6] 💡 Approach 1: Two Pointers (Optimal) Since both arrays are already sorted, we can use a two-pointer technique. 👉 Compare elements from both arrays and pick the smaller one each time. ✅ Time Complexity: O(n + m) ✅ Space Complexity: O(n + m) def merge_sorted_arrays(arr1, arr2): i, j = 0, 0 merged = [] while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: merged.append(arr1[i]) i += 1 else: merged.append(arr2[j]) j += 1 # Add remaining elements merged.extend(arr1[i:]) merged.extend(arr2[j:]) return merged 💡 Approach 2: Using Built-in Sort (Not Optimal) Merge both arrays and then sort. ❌ Time Complexity: O((n+m) log(n+m)) def merge_sorted_arrays(arr1, arr2): return sorted(arr1 + arr2) ⚡ Key Takeaways ✔️ Two-pointer approach is efficient and interview-friendly ✔️ Works because arrays are already sorted ✔️ Foundation for advanced topics like merge sort #Python #CodingJourney #30DaysOfCode #LearnToCode #Programming #Developers #ProblemSolving #PythonBasics

To view or add a comment, sign in

Explore content categories