Moh Ramjan’s Post

🚀 Day 33 of My DSA Journey | Optimized Approach 💡 Today I solved one of the classic problems from LeetCode: Merge Sorted Array 🔥 🧩 Problem Understanding Given two sorted arrays nums1 and nums2, we need to merge them into a single sorted array. Constraint: nums1 already has enough space at the end to accommodate elements of nums2. 🐢 Brute Force Approach My first thought was: Copy all elements of nums2 into nums1 Sort the entire array ⏱️ Time Complexity: O((m+n)²) 👉 Works fine, but not efficient for interviews. ⚡ Optimized Approach (Two Pointer - Reverse Merge) Then I explored the optimal solution: 💡 Key Idea: Start filling from the end of nums1 Compare elements from the back of both arrays Place the larger one at the last index 🔁 Steps: Set 3 pointers: i = m-1 (end of valid nums1) j = n-1 (end of nums2) k = m+n-1 (end of nums1 array) Compare and place elements from the back Handle remaining elements of nums2 if any 📌 Example nums1 = [1,2,3,0,0,0] nums2 = [2,5,6] Output: [1,2,2,3,5,6] ⏱️ Complexity Analysis Time: O(m+n) 🚀 Space: O(1) (In-place) 🎯 Key Learning 👉 When arrays are sorted, always think in terms of two pointers 👉 Filling from the end avoids unnecessary shifting 👉 Interviewers expect optimization, not just working code 🙏 Gratitude Grateful for continuous learning and improvement every single day 💯 🔥 Consistency Note Small steps daily → Big results over time 🚀 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode #SoftwareEngineering #InterviewPrep #DataStructures #Algorithms

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories