Finding Common Numbers in Three Sorted Arrays with Python

🚀 Day 39/100 – Find Common Elements in Three Sorted Arrays Today I learned how to find the common numbers in three sorted arrays using an efficient approach. 🧠 Problem Statement: Given three sorted arrays, find the elements that are common in all three. 💻 Example: # Three sorted arrays arr1 = [1, 5, 10, 20, 40, 80] arr2 = [6, 7, 20, 80, 100] arr3 = [3, 4, 15, 20, 30, 70, 80, 120] # Output: [20, 80] ⚙️ Approach: ✅ Use three pointers (one for each array). ✅ Move pointers smartly to compare elements. ✅ If all three are equal → add to result. ✅ If not, move the pointer of the smallest value forward. 🧩 Code: def findCommon(arr1, arr2, arr3): i = j = k = 0 common = [] while i < len(arr1) and j < len(arr2) and k < len(arr3): if arr1[i] == arr2[j] == arr3[k]: common.append(arr1[i]) i += 1 j += 1 k += 1 elif arr1[i] < arr2[j]: i += 1 elif arr2[j] < arr3[k]: j += 1 else: k += 1 return common print(findCommon(arr1, arr2, arr3)) 🎯 Output: [20, 80] 💡 Key Takeaway: Efficient pointer logic can save both time and space complexity, especially when dealing with sorted data. #100DaysOfCode #Day38 #Python #DSA #LearningEveryday #CodingChallenge #Arrays

To view or add a comment, sign in

Explore content categories