🔥 Day 108 of My DSA Challenge – Merge Sorted Array 🔷 Problem : 88. Merge Sorted Array 🔷 Goal : Merge two sorted arrays into one sorted array in-place inside nums1. The tricky part? nums1 already has extra space at the end — and we need to fill it without using extra arrays. 🔷 Key Insight : Use the two-pointer technique starting from the end — this avoids overwriting values in nums1. Pointer p1 → end of valid elements in nums1 Pointer p2 → end of nums2 Pointer idx → last index in final merged array Place the largest element first by comparing from the end. 🔷 Approach : 1️⃣ Start from the last elements of both arrays 2️⃣ Compare and place the greater one at the end 3️⃣ Move pointers backwards 4️⃣ If nums2 still has elements, copy them This gives us O(m + n) time and O(1) extra space ✅ Sometimes the most elegant solutions are not about building new structures but smartly reusing what you already have. Two-pointer technique continues to be a powerful tool in array problems 💪 #Day108 #100DaysOfCode #LeetCode #DSA #Java #TwoPointers #Arrays #CodingChallenge #Algorithm #InPlaceAlgorithms #ProblemSolving #Programming #SoftwareEngineering #TechJourney #DeveloperJourney #CodeEveryday #LearnDSA #GrowthMindset #EngineerMindset #LogicBuilding
Merging Sorted Arrays in-place with Two Pointers
More Relevant Posts
-
Day 55 of My DSA Challenge Problem: Count the number of triplets in an array that can form a valid triangle. Concept Recap: For any three sides to form a triangle, the sum of any two sides must be greater than the third side. Optimized Approach: Instead of checking every triplet (which takes O(N³)), I sorted the array and used a two-pointer technique to bring it down to O(N²): Sort the array. Fix the largest side (arr[k]) and use two pointers (i, j) to find pairs where arr[i] + arr[j] > arr[k]. If the condition holds, all elements between i and j can form valid triangles. Count and move pointers accordingly. Time Complexity: O(N²) Space Complexity: O(1) Takeaway: Sorting combined with the two-pointer approach often transforms brute-force solutions into elegant and efficient ones. #Day55 #DSAChallenge #TwoPointerTechnique #Sorting #Optimization #Java #ProblemSolving #DataStructures #Algorithms #CodingChallenge #GeeksforGeeks #LeetCode #100DaysOfCode #ProgrammersJourney #TechLearning
To view or add a comment, sign in
-
-
✨ Day 101 of My DSA Challenge – Magnetic Force Between Two Balls 🔷 Problem: 1552. Magnetic Force Between Two Balls 🔷 Goal: Place m balls into sorted basket positions such that the minimum magnetic force (i.e., minimum distance between any two balls) is as large as possible. 🔷 Key Insight: This is another brilliant Binary Search on the Answer problem. Instead of directly computing distances, we binary search for the maximum possible minimum distance that still allows placing all balls. Here’s how the logic works: 1️⃣ Sort all basket positions. 2️⃣ Use binary search on the range of possible distances (0 to max(position) - min(position)). 3️⃣ For each middle distance mid, check feasibility using a greedy approach — place balls while maintaining at least mid distance apart. 4️⃣ If it’s possible → try a larger distance. If not → reduce the distance. 🔷 My Java Approach: Implemented a helper function isPossible() to check if we can place all balls for a given minimum distance. Used Binary Search to maximize that minimum distance. 🔷 Complexity: Time → O(n × log(maxDist)) Space → O(1) This problem beautifully blends sorting, binary search, and greedy placement — showing how abstract concepts like “searching on the answer” translate into real algorithmic reasoning. Every new day strengthens my foundation in Binary Search patterns, sharpening both logic and implementation clarity. 🚀 #Day101 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #BinarySearch #GreedyAlgorithm #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #LearnToCode #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
DSA Practice – Day 48 🚀 Problem: Sort Array by Parity(LeetCode 905) Problem Statement: Given an integer array nums, move all even integers to the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. ⚡ Brute Force Approach: Create a new array. First, add all even numbers from nums to it. Then, add all odd numbers. Return the new array. Time Complexity: O(n) Space Complexity: O(n) (because of the extra array) ⚡ Optimal Approach (Two Pointer Technique): Use two pointers — one at the start (left) and one at the end (right). If the left element is odd and the right is even, swap them. Move pointers accordingly until they meet. This sorts even and odd numbers in-place without extra space. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: How to use the two-pointer approach for in-place array rearrangement. Simple logic can drastically reduce space usage in problems like these. #DSA #LeetCode #Java #Arrays #TwoPointer #ProblemSolving #Coding #InterviewPrep
To view or add a comment, sign in
-
-
📌 Day 153 of Coding - Maximum Frequency of an Element After Operations I (LeetCode - Medium) 🎯 Goal: Given an integer array nums, an integer range k, and a number of operations, determine the maximum possible frequency of any number after performing up to numOperations modifications - where each operation can change a number by at most k. 💡Approach & Debugging: Found the maximum value in the array and created a frequency prefix array. For each possible target value i, calculated the total numbers within the [i - k, i + k] range. The frequency of i could be increased using available operations on nearby elements. Kept track of the best achievable frequency. ✔️ Time Complexity: O(N + M) - where M is the value range up to max(nums) + k. ✔️ Space Complexity: O(M) 🧠Key Takeaways: Prefix sums + frequency arrays are powerful for range-based computations. Always optimize loops around range-based frequency calculations. #Day153 #LeetCode #Arrays #PrefixSum #Frequency #Java #ProblemSolving #DSA #CodingChallenge #Algorithms #100DaysOfCode #InterviewPrep #SoftwareEngineering #DataStructures #CodeNewbie #ProgrammersLife
To view or add a comment, sign in
-
-
🔥 Day 109 of My DSA Challenge – Intersection of Two Arrays 🔷 Problem : 349. Intersection of Two Arrays 🔷 Goal : Return the unique intersection of two integer arrays. Order doesn’t matter, but duplicates should not appear in the result. 🔷 Key Insight : This is a set / hashmap based lookup problem. We store elements from the first array, then check if elements from the second array exist in it. To ensure uniqueness, we remove the element once counted, so duplicates don't appear. 🔷 Approach : 1️⃣ Add all elements of nums1 to a HashMap 2️⃣ Traverse nums2 3️⃣ If the element exists in the map → add to result & remove from map 4️⃣ Convert list to array and return Time Complexity: O(n + m) Space Complexity: O(n) Sometimes the simplest tools — like HashMaps/Sets — give the cleanest solutions. Learning to choose the right data structure = faster logic + cleaner code 💪 #Day109 #100DaysOfCode #LeetCode #DSA #Java #HashMap #DataStructures #CodingChallenge #Algorithm #ProblemSolving #Programming #SoftwareEngineering #TechJourney #DeveloperJourney #CodeEveryday #LearnDSA #LogicBuilding #GrowthMindset #EngineerMindset
To view or add a comment, sign in
-
💡 Day 97 of My DSA Challenge – Single Element in a Sorted Array 🔷 Problem : 540. Single Element in a Sorted Array 🔷 Goal : Find the single element that appears only once in a sorted array where all other elements appear exactly twice, in O(log n) time and O(1) space. 🔷 Key Insight : The array is sorted, and elements appear in pairs — except for one. We can use Binary Search on Indices : Check the mid element and compare it with neighbors. If mid is unique → return it. Otherwise, depending on whether the pair is on the left or right and the parity of the remaining elements, move left or right. This works because the single element shifts the pairing pattern in the array, allowing us to discard half the search space each time. 🔷 My Java Approach : 1️⃣ Binary search over array indices. 2️⃣ Compare mid with neighbors to detect the single element. 3️⃣ Adjust search space using parity logic. 🔷 Complexity : Time → O(log n) Space → O(1) Binary search isn’t just for sorted numbers — it can also be applied to patterns and structural properties in arrays. Recognizing such patterns allows efficient solutions even when the array has special constraints. 🚀 #100DaysOfCode #Day97 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
Leveling Up Every Day Continuing my #100DaysOfLeetCode journey! #Day 34/100 LeetCode Challenge: Problem : Next Permutation ###31 LeetCode : https://lnkd.in/gCgwuccf Today I solved one of the classic problems in array manipulation — Next Permutation. The goal is to rearrange the numbers to form the next lexicographically greater permutation of the sequence. If such a rearrangement isn’t possible (the array is in descending order), we simply return the smallest possible order (ascending). Understanding the Logic Let’s say we have an array: [1, 2, 3] The next permutation would be [1, 3, 2] If the array is [3, 2, 1], it’s already the highest permutation — so we reverse it to [1, 2, 3]. Step-by-Step Approach Find the first decreasing element when traversing from the right. → This identifies the pivot point where the next permutation change must occur. Find the element just greater than this pivot (on the right side). → Swap these two elements to slightly increase the sequence lexicographically. Reverse the part after the pivot → This ensures the remaining sequence is the smallest possible order after the swap. Key Insights Runs in O(n) time — just a few traversals of the array. Uses O(1) extra space — all operations are in-place. A perfect example of logic, observation, and attention to detail working together. Personal Note This problem tested my understanding of how permutations and lexicographical ordering actually work behind the scenes. It’s a great exercise to sharpen problem-solving and array manipulation skills in Java. #100DaysOfCode #100DaysOfLeetCode #Java #ProblemSolving #DSA #CodingJourney #LeetCode #CodingChallenge #Programming #SoftwareEngineering #DataStructures #Algorithms #TechLearning #Math #CodeEveryday #JavaProgramming #LearnToCode #DeveloperJourney #DailyCoding #Developerlife #Coderlife #LearnToCode #ConsistendLearning #LearningEveryday
To view or add a comment, sign in
-
-
🚩 Problem: 239. Sliding Window Maximum 🔥 Day 51 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return an array containing the maximum value in every sliding window of size k. This is a classic sliding window problem that looks heavy, but with the right data structure, the solution is clean and O(n). 🧠 Intuition: A normal approach checks each window → O(n × k) (too slow). Instead, use a Deque to store indices of useful elements: The deque always keeps elements in decreasing order. The front of the deque is always the maximum of the current window. Remove elements: Outside the current window Smaller than the new incoming element This gives us the maximum in O(1) per window ⇒ total O(n). ⚙️ Performance: ⏱️ Runtime: 28 ms 🚀 💪 Beats: 98.7% of Java solutions 💾 Memory: 63 MB ⚡ (Beats ~96% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(k) ✨ Key Takeaway: The Deque technique is one of the most powerful sliding window optimizations — turning a potentially quadratic problem into linear time with a clean and elegant solution. Link:[https://lnkd.in/gJTzhcR2] #100DaysOfLeetCode #Day51 #Problem239 #SlidingWindowMaximum #Deque #SlidingWindow #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #CodingCommunity #ArjunInfoSolution #CodeNewbie #Programming #TechCareers #CareerGrowth #ZeroToHero #LearnToCode #CodingIsFun #ComputerScience #JavaDeveloper #DeveloperJourney #AI #MachineLearning #UnityGameDev #GameDeveloper
To view or add a comment, sign in
-
-
🚀 Day 413 of #500DaysOfCode 💡 Problem: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 🧩 Difficulty: Medium Today’s challenge was an interesting mix of GCD logic and array transformation! We’re given an array of positive integers and can repeatedly pick adjacent elements — replacing one of them with their GCD. Our goal? Make all elements equal to 1 in the minimum number of operations. 🧠 Key Idea: If there’s already a 1 in the array → just need (n - countOf1s) operations. Otherwise, find the shortest subarray whose GCD equals 1. It takes (len - 1) steps to make the first 1. Then (n - 1) steps to spread that 1 across the array. If no subarray has GCD = 1 → return -1. 📘 Concepts Used: Greatest Common Divisor (GCD) Sliding subarray search Mathematical optimization ✨ This problem reinforced how number theory meets logic in coding — sometimes the simplest mathematical idea (like GCD) leads to elegant solutions! #Day413 #LeetCode #Java #ProblemSolving #CodingChallenge #LearnEveryday #500DaysOfCode #MathInCoding
To view or add a comment, sign in
-
-
🔥 LeetCode Daily Challenge – Day 14 🧩 Problem: 3312. Number of Substrings With One’s Count at Least Square of Zero’s Count 🚀 Approach: Zero-Positions + Prefix Optimization Today’s problem was an interesting blend of math and string analysis. The key insight was recognizing that zero-count grows slowly, and feasible substrings can be efficiently tracked using prefix logic and previous zero positions. ⭐ My approach: Precompute previous zero indices for fast block calculations Track zeros and compute required ones using ones ≥ zeros² Use a mathematical bound (sqrt(n)) to safely prune infeasible ranges Achieved near-linear behavior on large inputs Clean, optimized, and significantly faster than brute force. 💡 This method avoids triple-nested loops and leverages structure in binary strings. 📈 Result: ✔️ Accepted ⚡ Runtime: 115ms (Beats 83.33%) 📦 Memory: 47.07MB (Beats 26.85%) Day 14 streak still going strong! 🔥 #LeetCode #DailyChallenge #Java #DSA #ProblemSolving #DailyCodingChallenge #CodingStreak
To view or add a comment, sign in
-
Explore related topics
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