🚀 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
Moh Ramjan’s Post
More Relevant Posts
-
🚀 Day 25 of My DSA Journey – Mastering In-Place Array Manipulation Today I solved an interesting problem on LeetCode: 👉 Remove Duplicates from Sorted Array II 🔍 Problem Understanding Given a sorted array, the goal is to remove duplicates in-place such that each element appears at most twice, and return the new length. ⚠️ Constraint: No extra space allowed Modify array in-place 🧠 Brute Force Approach Use extra space (like ArrayList) Track frequency and rebuild array ❌ Not optimal due to O(n) space complexity ⚡ Optimized Approach (Two Pointer Technique) 💡 Key Idea: Since array is sorted, duplicates are adjacent. We can compare current element with the element 2 steps back. 🪜 Steps Start pointer i = 2 (since first 2 elements are always valid) Traverse from j = 2 → n-1 Check: If nums[j] != nums[i-2] → valid element Place it at index i and increment i 🧾 Code Snippet (Java) class Solution { public int removeDuplicates(int[] nums) { int i = 2; for(int j = 2; j < nums.length; j++) { if(nums[j] != nums[i-2]) { nums[i] = nums[j]; i++; } } return i; } } 🧪 Example Walkthrough Input: [1,1,1,2,2,3] Process: Allow only 2 occurrences Final array becomes: [1,1,2,2,3] Output: 5 ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ (In-place) 💡 Key Learning Sorted array → powerful advantage Two-pointer technique = must-know for interviews Comparing with i-2 is the trick 🔥 🙏 Gratitude Grateful for the consistency and learning curve. Every problem sharpens my logic a bit more! 📈 Consistency Note Showing up daily > being perfect occasionally 💯 #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #SoftwareEngineering #ProblemSolving #InterviewPrep #TechLearning
To view or add a comment, sign in
-
-
🚀 Day 23 of My DSA Journey – Clean & Efficient Deduplication Today I solved a classic and very important problem: 👉 Remove Duplicates from Sorted Array 🔍 Problem Understanding Given a sorted array, we need to remove duplicates in-place such that each element appears only once and return the new length. ⚠️ Constraints: No extra space allowed Maintain relative order 🧠 Brute Force Approach Use a Set or ArrayList to store unique elements Copy back to array ❌ Not optimal due to O(n) extra space ⚡ Optimized Approach (Two Pointer Technique) 💡 Key Idea: Since the array is sorted, duplicates are adjacent. We can maintain a pointer j to track the position of unique elements. 🪜 Steps Initialize j = 0 Traverse array using i If nums[j] != nums[i] Increment j Assign nums[j] = nums[i] Return j + 1 🧪 Example Walkthrough Input: [0,0,1,1,1,2,2,3,3,4] Process: Keep only unique elements Final array: [0,1,2,3,4] Output: 5 ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ 💡 Key Learning Sorted arrays simplify many problems Two-pointer approach is 🔑 for in-place operations Writing clean and minimal code matters in interviews 🙏 Gratitude Consistency is paying off. Small daily wins are building strong fundamentals 💪 📈 Consistency Note Discipline > Motivation. Showing up daily 🚀 #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #ProblemSolving #TechJourney #InterviewPreparation
To view or add a comment, sign in
-
-
🔁 DSA Pattern #3 — Two Pointers One of the best ways to improve in problem solving is learning how to turn a slow O(n²) solution into a faster one. The Two Pointers pattern helps you do that. Instead of checking every pair again and again, we use two pointers and move them smartly based on the condition. This saves time and makes the solution cleaner. Here are the main types: → Both Ends Use one pointer from left and one from right. Common in 2Sum, 3Sum, Container With Most Water, Trapping Rain Water, and palindrome problems. → Slow / Fast Fast pointer checks elements, slow pointer stores valid results. Used in remove duplicates and in-place array problems. → Two Arrays One pointer on each array or string. Used in merge sorted arrays, subsequence, and intersection problems. → Dutch National Flag Use three pointers: low, mid, high. Helpful in sorting 0s, 1s, and 2s type problems. → k-Sum Problems For bigger sum problems, use loops first and then apply Two Pointers in the remaining part. Quick trick: `sum < target` → move left pointer `sum > target` → move right pointer `sum == target` → answer found ✅ Why learn this pattern? ✔ Very common in coding interviews ✔ Helps optimize brute-force solutions ✔ Easy to apply on arrays and strings ✔ Builds strong problem solving skills I’ve shared simple notes, reusable templates, and practice problems here: 🔗 GitHub Repository: https://lnkd.in/gyDaTt6S DSA Pattern Series: ✅ Pattern #1 — Binary Search ✅ Pattern #2 — Sliding Window 🔁 Pattern #3 — Two Pointers Save this for interview preparation 🚀 #DSA #LeetCode #TwoPointers #Algorithms #CodingInterview #Java #InterviewPreparation #dsapattern #patterns
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 126/360 🚀 📌 Topic: Array + Backtracking (Recursion) 🧩 Problem: Combination Sum II Problem Statement: Find all unique combinations in an array where numbers sum up to a target. Each number can be used only once, and duplicate combinations are not allowed. 🔍 Example: Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6], [1,2,5], [1,7], [2,6]] 💡 Approach: Backtracking + Pruning 1️⃣ Step 1 – Sort the array to handle duplicates easily 2️⃣ Step 2 – Use recursion to pick elements and reduce target 3️⃣ Step 3 – Skip duplicates & backtrack after each recursive call 👉 Use condition to skip duplicates: if(i > ind && arr[i] == arr[i-1]) continue; 👉 Stop early if element exceeds target (pruning) ⏱ Complexity: Time: O(2^n) Space: O(k * x) (for storing combinations) 📚 Key Learning: Sorting + duplicate skipping is the key trick to avoid repeated combinations in backtracking problems. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode
To view or add a comment, sign in
-
-
🧱 𝗜 𝗦𝗼𝗹𝘃𝗲𝗱 𝗮 “𝗩𝗶𝘀𝘂𝗮𝗹” 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗨𝘀𝗶𝗻𝗴 𝗢𝗻𝗹𝘆 𝗮 𝗦𝘁𝗮𝗰𝗸 — 𝗡𝗼 𝗚𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗡𝗲𝗲𝗱𝗲𝗱 Today’s problem looked visual and innocent: 𝗚𝗶𝘃𝗲𝗻 𝗯𝗮𝗿 𝗵𝗲𝗶𝗴𝗵𝘁𝘀 𝗼𝗳 𝗮 𝗵𝗶𝘀𝘁𝗼𝗴𝗿𝗮𝗺 (𝘄𝗶𝗱𝘁𝗵 = 𝟭), 𝗳𝗶𝗻𝗱 𝘁𝗵𝗲 𝗹𝗮𝗿𝗴𝗲𝘀𝘁 𝗿𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲 𝗮𝗿𝗲𝗮. This is the classic problem from 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 — and it’s a beautiful lesson in how 𝗺𝗼𝗻𝗼𝘁𝗼𝗻𝗶𝗰 𝘀𝘁𝗮𝗰𝗸𝘀 𝗰𝗼𝗻𝘃𝗲𝗿𝘁 𝗴𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗶𝗻𝘁𝗼 𝗶𝗻𝗱𝗶𝗰𝗲𝘀. 🧠 𝗧𝗵𝗲 𝗡𝗮𝗶𝘃𝗲 𝗧𝗵𝗼𝘂𝗴𝗵𝘁 (𝗮𝗻𝗱 𝘄𝗵𝘆 𝗶𝘁 𝗳𝗮𝗶𝗹𝘀) For every bar i, try expanding left and right until you hit a smaller bar. That’s O(n) per index -> O(n²). Too slow for n=10^5. So the real question becomes: For each bar, how far can it extend without hitting a smaller height? That is the entire problem. 💡 𝗞𝗲𝘆 𝗜𝗱𝗲𝗮 — 𝗡𝗲𝗮𝗿𝗲𝘀𝘁 𝗦𝗺𝗮𝗹𝗹𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 For every index i: 1. Find the first smaller bar on the left 2. Find the first smaller bar on the right A monotonic increasing stack gives both in linear time. ▶️ 𝗟𝗲𝗳𝘁 𝗦𝗰𝗮𝗻 (𝗟 -> 𝗥) Pop until the top is strictly smaller. That index defines the left boundary. ◀️ 𝗥𝗶𝗴𝗵𝘁 𝗦𝗰𝗮𝗻 (𝗥 -> 𝗟) Same logic to get the right boundary. Now each bar knows the exact range where it is the minimum. ⏱️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 Each index pushed/popped once → O(n) Space → O(n) ✨ 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 1. “Nearest smaller element” is a powerful pattern 2. Monotonic stacks turn nested loops into linear scans 3. Think: If this bar is the minimum, how wide can the rectangle be? A visual problem, solved with clean stack discipline. #DataStructures #Algorithms #MonotonicStack #Java #ProblemSolving #CodingInterview #Stack #DSA #LeetCode #Coding #Programmer #SoftwareEngineer #InterviewPrep #CompetitiveProgramming #100DaysOfCode #Tech #Learning #ProblemSolvingSkills
To view or add a comment, sign in
-
-
Day 7 of My DSA Journey - Merge Sorted Array Continuing the journey with consistency and deeper understanding of core patterns. Problem: Merge Sorted Array https://lnkd.in/dEEkCJnS Given two sorted arrays nums1 and nums2, merge them into a single sorted array in-place inside nums1. Approach: 1. Initialize three pointers: 2. i = m - 1 (last valid element in nums1) 3. j = n - 1 (last element in nums2) 4. k = m + n - 1 (last index of nums1) 5. Compare nums1[i] and nums2[j] 6. Place the larger element at nums1[k] 7. Move the corresponding pointer (i or j) backward 8. Decrement k after each placement 9. If elements remain in nums2, copy them into nums1 Time Complexity: O(m + n) Space Complexity: O(1) What I Learned Today 1. Merging from the end avoids overwriting useful data in nums1 2. Two-pointer technique is extremely powerful for sorted arrays 3. Thinking in reverse simplifies in-place problems 4. Edge cases like empty arrays (m = 0 or n = 0) are important 5. This pattern is widely used in merge sort and other problems This is Day 7 focusing on strengthening problem-solving patterns. I will continue sharing more insights and learnings as I progress. If you are also preparing for coding interviews, let’s grow together #DSA #CodingJourney #ProblemSolving #Java #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 33 of My DSA Journey – Reverse Vowels of a String (LeetCode) Today I worked on a really interesting problem: Reverse Vowels of a String — and learned how powerful the two-pointer approach can be. 🔍 Problem Understanding We are given a string, and we need to reverse only the vowels while keeping the rest of the characters in the same position. 👉 Example: Input: "hello" Output: "holle" 🐢 Brute Force Approach Extract all vowels into a separate list Reverse that list Traverse the string again and replace vowels one by one ⛔ Time Complexity: O(n) ⛔ Space Complexity: O(n) (extra storage used) ⚡ Optimized Approach (Two Pointer) Instead of extra space, I used two pointers (i, j): Steps: Initialize: i = 0 (start) j = n-1 (end) Move i forward until it finds a vowel Move j backward until it finds a vowel Swap both vowels Repeat until i < j 🧠 Example Walkthrough Input: "leetcode" i → 'e', j → 'e' → swap i → 'e', j → 'o' → swap Final Output: "leotcede" ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ (in-place) 💡 Key Learning Two-pointer approach is extremely useful for string manipulation problems Always try to reduce extra space usage Clean condition handling (like checking vowels) matters a lot in interviews 🙏 Thanks to LeetCode for such great problems that strengthen problem-solving skills. 📈 Consistency is the key — small steps daily lead to big results. #DSA #Java #LeetCode #ProblemSolving #CodingJourney #100DaysOfCode #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 76 of #100daysofcode Deep Dive into Linked Lists (Reverse Nodes in K-Group) Today’s problem pushed me to think beyond basic linked list operations. I worked on reversing nodes in groups of size k which is a classic interview problem that tests not just logic, but also how well you understand pointers. At first glance, the problem looks similar to reversing a linked list—but the twist is that you don’t reverse the entire list at once. Instead, you reverse it in chunks, and if the remaining nodes are fewer than k, you leave them as they are. This small condition makes the problem much more interesting and slightly tricky. 🔹 My Approach & Understanding: I broke the problem into smaller steps to make it manageable: 1. First, I checked whether there are at least k nodes available. If not, no reversal is needed. 2. Then, I reversed exactly k nodes using the standard three-pointer approach (prev, curr, next). 3. After reversing the first k nodes, I recursively solved the remaining part of the list. 4. Finally, I connected the reversed portion with the rest of the list. This problem really helped me understand how powerful pointer manipulation is. One small mistake in updating pointers can completely break the logic, so careful thinking is required at every step. 🔹 Example: Input: `1 → 2 → 3 → 4 → 5`, k = 2 Output: `2 → 1 → 4 → 3 → 5` 🔹 Key Learnings: ✔ Breaking problems into smaller subproblems makes them easier to solve ✔ Recursion can simplify complex linked list problems ✔ Pointer handling is one of the most important skills in DSA ✔ Edge cases (like remaining nodes < k) are crucial in interviews 🔹 Challenges Faced: Initially, I struggled with connecting the reversed part to the remaining list correctly. It took some time to understand how recursion helps in managing the rest of the list cleanly. 🔹 Takeaway: Problems like this are not just about coding—they train your brain to think logically and systematically. Each day, I feel more confident handling complex data structures. Consistency is the real game changer. Showing up every day, even when it’s tough, is what builds real skill over time. On to Day 77 💪 #Day76 #100DaysOfCode #DSA #LinkedList #LeetCode #CodingJourney #ProblemSolving #PlacementPreparation #SoftwareEngineering #TechGrowth #Consistency #KeepLearning
To view or add a comment, sign in
-
-
🚀 Day 71 of Consistency — 111 LeetCode Problems Solved! Today felt like a real breakthrough. I solved one of the most asked “Medium” interview problems — Product of Array Except Self (LeetCode 238) — and hit 95%+ runtime performance (2ms) without using division. But more than the result, here’s what actually mattered 👇 🧠 What I Learned Today Instead of brute force or nested loops, I used a Prefix + Postfix synchronization approach: 👉 Build left products (prefix) 👉 Build right products (postfix) 👉 Combine them in one pass This simple shift: ✔ Eliminates division ✔ Keeps time complexity at O(n) ✔ Makes the solution scalable for large data ⚡ Key Insight Most optimization problems aren’t about “doing more” — they’re about restructuring how data flows. Today’s takeaway: Think in passes, not in loops. 📊 My Progress So Far • ✅ 111 Problems Solved • 🔥 71-Day Streak • 📈 Strong focus on Medium-level problems • ⚡ Improving intuition for optimized solutions 💡 Why This Matters (For You Too) If you're preparing for coding interviews or improving problem-solving: Start identifying patterns (prefix sum, hashing, two pointers) Focus on time complexity thinking early Practice consistency > intensity These are the exact skills companies look for. 📸 I’ve also shared my LeetCode snapshot! #LeetCode #DSA #CodingJourney #SoftwareEngineering #ProblemSolving #Java #TechGrowth #Consistency #100DaysOfCode #InterviewPrep
To view or add a comment, sign in
-
-
🚀 #100DaysOfDSA – Day 9 Today’s problem was one of the most popular in DSA — Maximum Subarray Sum. 🔍 Problem Statement: Given an integer array, find the contiguous subarray with the largest sum. 💡 Brute Force Approach: Check all possible subarrays and calculate their sums. 🧠 Idea: ✔️ Generate all subarrays ✔️ Compute sum for each ✔️ Track maximum ⚠️ Time Complexity: O(n²) (or O(n³) if sum is recalculated every time) ⚠️ Space Complexity: O(1) ⚡ Optimized Approach (Kadane’s Algorithm): 💡 Key Insight: At every step, decide: 👉 Start a new subarray 👉 OR continue the existing one 🧠 Logic: ✔️ sum = max(nums[i], sum + nums[i]) ✔️ Track maximum sum globally ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Kadane’s Algorithm): class Solution { public int maxSubArray(int[] nums) { int sum = 0; int max_sum = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { sum = Math.max(nums[i], sum + nums[i]); max_sum = Math.max(max_sum, sum); } return max_sum; } } 🔥 Takeaway: Brute force helps understand the problem, but recognizing patterns like Kadane’s Algorithm helps optimize from O(n²) → O(n). That’s the real DSA growth 📈 #100DaysOfDSA #100DaysChallenge #CodingJourney #Java #ProblemSolving #InterviewPrep #KadaneAlgorithm #DSA
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development