🚀 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
Moh Ramjan’s Post
More Relevant Posts
-
🔥 DSA Challenge – Day 125/360 🚀 📌 Topic: Recursion 🧩 Problem: Combination Sum Problem Statement: Given an array of distinct integers and a target, return all unique combinations where numbers sum up to the target. Same element can be used multiple times. 🔍 Example: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] 💡 Approach: Backtracking 1️⃣ Step 1 – Start from index 0 and try picking each element 2️⃣ Step 2 – If element ≤ target, include it and reduce target 3️⃣ Step 3 – Backtrack (remove element) and move to next index ✔ Use recursion to explore all possibilities ✔ Reuse same element (stay on same index) ✔ Stop when target becomes 0 (valid answer) ✔ Skip when index reaches end ⏱ Complexity: Time: O(2^n * k) (k = avg length of combination) Space: O(k * x) (x = number of combinations) 📚 Key Learning: Backtracking is all about making choices, exploring, and undoing them efficiently. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode #Backtracking 🚀
To view or add a comment, sign in
-
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 15. 3Sum 🧠 Approach & Smart Solution: This classic medium-level problem is a great test of optimizing loops! A brute-force O(n³) approach would easily hit a Time Limit Exceeded (TLE). Instead, I optimized it to O(n²) using the Sorting + Two-Pointer technique. • Pseudo-code: First, sort the given array. Iterate through the array with an index 'i'. Skip duplicate elements to avoid duplicate triplets. Set two pointers: 'j' right after 'i', and 'k' at the end of the array. While 'j' is less than 'k': Calculate the sum of elements at i, j, and k. If the sum is 0, we found a valid triplet! Add it to the result list, and smoothly skip any duplicate values for both 'j' and 'k'. If the sum is less than 0, increment 'j' to increase the sum. If the sum is greater than 0, decrement 'k' to decrease the sum. By sorting first, we can systematically eliminate duplicate triplets and efficiently navigate towards the target sum without redundant checks! ⏱️ Time Complexity: O(n²) (Sorting takes O(n log n), and the two-pointer search takes O(n²)) 📦 Space Complexity: O(1) (Auxiliary space, excluding the space required for the output list) 📊 Progress Update: • Streak: 6 Days 🔥 • Difficulty: Medium • Pattern: Two Pointers / Sorting 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering the two-pointer technique on sorted arrays is a massive level-up for optimizing complex algorithms! 💡 #LeetCode #DSA #TwoPointers #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Starting a New Topic: Recursion 🔥 DSA Challenge – Day 118/360 📌 Topic: String 🧩 Problem: String to Integer (atoi) Problem Statement: Convert a string into a 32-bit signed integer while handling spaces, sign, non-digit characters, and overflow. 🔍 Example: Input: " -42" Output: -42 💡 Approach: Recursion + Parsing 1️⃣ Step 1 – Skip leading spaces and detect sign (+ / -) 2️⃣ Step 2 – Recursively process each digit and build the number 3️⃣ Step 3 – Check overflow at every step and return result ⏱ Complexity: Time: O(n) Space: O(n) (recursive stack) 📚 Key Learning: Always handle overflow during computation, not after building the full number. Recursion simplifies problems by breaking them into smaller subproblems. 💭 New Topic Journey Begins: Excited to dive deep into Recursion and master it step by step! 💪 #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #118DaysOfCode #LeetCode #Recursion
To view or add a comment, sign in
-
-
🚀 Solved “Search Insert Position” using Binary Search on LeetCode! Today I worked on an interesting problem where the goal is to find the index of a target element in a sorted array. If the target is not present, we return the index where it should be inserted to maintain sorted order. 🔍 Approach: Instead of using a linear search (O(n)), I implemented an efficient Binary Search (O(log n)) approach. 💡 Key Learning: One important detail is calculating the middle index safely: mid = low + (high - low) / 2 This avoids potential integer overflow compared to (low + high) / 2 and ensures correct behavior even for large inputs. ⚙️ Logic: If target == arr[mid] → return mid If target > arr[mid] → search right half Else → search left half If not found → return ‘low’ as the correct insert position 📈 Result: Achieved 100% performance on LeetCode 🚀 This problem reinforced my understanding of: ✔ Binary Search fundamentals ✔ Edge case handling ✔ Writing optimized and safe code Looking forward to solving more problems and improving problem-solving skills! #LeetCode #BinarySearch #Java #DataStructures #Coding #ProblemSolving
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
-
-
📘 DSA Journey — Day 31 Today’s focus: Binary Search for boundaries and square roots. Problems solved: • Sqrt(x) (LeetCode 69) • Search Insert Position (LeetCode 35) Concepts used: • Binary Search • Search space reduction • Boundary conditions Key takeaway: In Sqrt(x), the goal is to find the integer square root. Using binary search, we search in the range [1, x] and check mid * mid against x to narrow down the answer. This avoids linear iteration and achieves O(log n) time. In Search Insert Position, we use binary search to find either: • The exact position of the target, or • The correct index where it should be inserted The key idea is that when the target is not found, the final position of the left pointer gives the correct insertion index. These problems highlight how binary search is not just for finding elements, but also for determining positions and boundaries efficiently. Continuing to strengthen fundamentals and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 62 of My DSA Journey Today I worked on Factorial Trailing Zeroes (LeetCode 172) 💡 Initially, I thought of calculating the full factorial, but that approach quickly becomes inefficient for large inputs ❌ 🧠 Key Insight: Trailing zeros are formed by multiples of 10 (2 × 5). Since factors of 2 are already abundant, the real task is to count how many times 5 appears in numbers up to n. 📌 Example: For n = 25 → multiples of 5 contribute extra factors → result = 6 trailing zeros ✅ 💭 What I learned today: Don’t always go with brute force Look for hidden mathematical patterns Optimization often comes from changing perspective Staying consistent and learning something new every day 🙌 #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
“What I learned after solving 300+ LeetCode problems 👇” At the beginning, I made a mistake. I kept solving random problems every day thinking: “More problems = more skill” But I was wrong. I realized that solving problems randomly is mostly a waste of time if you don’t understand the pattern behind them. Everything changed when I started focusing on patterns instead of problems. Here are some important patterns I learned: • Sliding Window • Two Pointers • Prefix Sum • Binary Search • Recursion & Backtracking • Linked List Patterns • Stack & Monotonic Stack • Hashing / Frequency Count Once you understand these patterns: You don’t need to solve 1000 problems. You start recognizing solutions instantly. Now when I see a problem, I don’t panic. I ask: 👉 “Which pattern does this belong to?” That one question changed everything for me. Still learning, but now with direction 🚀 #DSA #LeetCode #Java #BackendDevelopment #CodingJourney
To view or add a comment, sign in
-
🚀 Solved LeetCode Problem #22 – Generate Parentheses Today I worked on an interesting recursion + backtracking problem that really strengthens understanding of constraint-based generation. 🔍 Problem Insight: Given n pairs of parentheses, generate all combinations of well-formed parentheses. 💡 Key Idea: Instead of generating all combinations and filtering invalid ones, we build only valid strings by: Adding '(' only when we still have some left Adding ')' only when it won’t break validity (i.e., open > close) 🧠 This ensures we never create invalid sequences, making the solution efficient. ⚙️ Approach Used: Backtracking (DFS) with two counters: open → number of '(' used close → number of ')' used 📈 Complexity: Time complexity follows Catalan Numbers → grows approximately as O(4^n / √n) ✨ Key Learning: This problem highlights how smart constraints in recursion can avoid unnecessary computation and lead to optimal solutions. 📌 Problems like this are great for mastering: Recursion Backtracking Combinatorial generation #LeetCode #Coding #DSA #Recursion #Backtracking #Java #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 15 of My DSA Journey Today’s problem: Array Rank Transform 💡 Problem Insight: Given an array, replace each element with its rank when the array is sorted. Rank starts from 1 Equal elements → same rank Ranks must be continuous (no gaps) 🧠 Approach: 🔹 Clone and sort the array 🔹 Use a HashMap to assign ranks to unique elements 🔹 Traverse original array and replace values using the map ⚡ Key Learning: 👉 This is a classic example of Coordinate Compression 👉 Helps reduce large values into a smaller ranked range 💻 Code Logic: Sort copy of array Assign rank only if element not already mapped Replace original values using the map 📊 Result: ✅ 43 / 43 test cases passed ⏱ Runtime: 31 ms 📈 Beat: 58.58% 💾 Memory: 74.74 MB (85.14% better than others) 💭 Takeaway: Simple problems can test clean thinking + handling duplicates properly. Hashing + sorting is a powerful combo 🔥 🔥 Consistency Check: Day 15 Complete Building discipline one problem at a time. #DSA #CodingJourney #LeetCode #Java #ProblemSolving #Consistency #100DaysOfCode
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