Find Smallest Common Element in Sorted Arrays

This title was summarized by AI from the post below.

🚀 LeetCode Day Problem Solving 🚀 Day-83 📌 Problem: Find the smallest common element present in both sorted arrays 🔥 If no common element exists → return -1 🧠 Example: Input: nums1 = [1,2,3] nums2 = [2,4] ✅ Output: 2 💡 Why? Common elements are: [[2]] Smallest common element = 2 ✅ 💡 Key Insight (Very Important 🔥): 👉 Both arrays are already SORTED ⚡ So instead of brute force checking every pair ❌ We can use: #️⃣ Two Pointer Technique 🚀 ⚡ Core Idea: Maintain pointers: ✔ i for nums1 ✔ j for nums2 Case 1️⃣: If: [nums1[i] = nums2[j]] ✅ Found smallest common element immediately because arrays are sorted 🔥 Case 2️⃣: If: [nums1[i] < nums2[j]] 👉 Move i forward because smaller value cannot match future larger values Case 3️⃣: If: [nums1[i] > nums2[j]] 👉 Move j forward 🧠 Why This Works? Since arrays are sorted: ✔ Once a smaller value is skipped, it can never become useful later So we eliminate unnecessary comparisons efficiently ⚡ ⚡ Algorithm: 1️⃣ Initialize: ✔ i = 0 ✔ j = 0 2️⃣ Traverse both arrays: ✔ If equal → return value ✔ Else move pointer with smaller value 3️⃣ If traversal ends → return -1 🔥 Example Walkthrough: nums1 = [1,2,3,6] nums2 = [2,3,4,5] Step 1: Compare: [1 \text{ and } 2] 1 < 2 👉 Move first pointer Step 2: Compare: [2 \text{ and } 2] ✅ Match found Answer = 2 📊 Complexity Analysis: ⏱ Time Complexity: [O(n+m)] where n and m are array sizes 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Two Pointer Technique ✔ Efficient traversal of sorted arrays ✔ Avoiding brute force comparisons 🔥 Day 83 Completed! Sorted arrays often unlock elegant linear-time solutions 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories