🚀 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
Remove Duplicates from Sorted Array in O(n) Time Complexity
More Relevant Posts
-
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
-
-
🚀 DSA Journey – Day 4-8 After learning loops and pattern problems, I moved to the next core topic — Arrays. 💡 Why Arrays Matter: Arrays are the foundation of most DSA problems. They are heavily used in: • Searching & Sorting • Sliding Window & Two Pointers • Dynamic Programming • Real-world systems (data storage & processing) 📚 Problems I Solved (Striver A2Z + NeetCode): • Find Maximum & Minimum Element • Check if Array is Sorted • Reverse an Array • Second Largest Element • Move Zeros to End • Remove Duplicates from Sorted Array • Two Sum 🧠 Array Cheatsheet (Beginner Friendly): ✔ Traversal → Always start with a loop (O(n)) ✔ Max/Min → Keep a variable and update while traversing ✔ Reverse → Use two pointers (start & end) ✔ Duplicates → Use two pointers / set ✔ Two Sum → Use HashMap for O(n) optimization ⚡ Common Mistakes to Avoid: • Ignoring edge cases (empty array, single element) • Writing O(n²) when O(n) is possible • Not dry running before coding • Forgetting index-based thinking 🧠 What I Learned: • How to shift from brute force → optimized approach • Importance of time complexity in interviews • Same pattern can solve multiple problems 📌 Takeaway: If you master arrays, you unlock 50% of DSA problem-solving patterns. #DSA #Arrays #ProblemSolving #Java #CodingJourney
To view or add a comment, sign in
-
-
🚀 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
To view or add a comment, sign in
-
-
Day 1 of problem solving: 🚀 Solved 4 interesting DSA problems today — sharing quick approaches + core logic 👇 1️⃣ Detect Cycles in 2D Grid Used DFS + parent tracking. The key idea is to traverse only same-valued adjacent cells and detect whether we revisit an already visited cell that is not the immediate parent. 🔹 Algorithm: Graph Traversal (DFS) 🔹 Logic: visited[][] + previous cell coordinates 2️⃣ Common Elements in 3 Sorted Arrays Applied the 3-pointer technique. Since all arrays are sorted, we move the pointer pointing to the smallest value until all three values match. 🔹 Algorithm: Two/Three Pointers 🔹 Logic: linear scan in O(n1 + n2 + n3) 3️⃣ Smallest Window Containing 0, 1 and 2 Solved using the Sliding Window approach. Expand the right pointer until the window contains all 3 digits, then shrink from the left to find the minimum valid window. 🔹 Algorithm: Sliding Window 🔹 Logic: frequency count + two pointers 4️⃣ Halloumi Boxes (Codeforces) A beautiful observation-based problem. If k = 1, no movement is possible, so the array must already be sorted. If k > 1, adjacent swaps become possible through reversal, meaning any array can be sorted. 🔹 Algorithm: Greedy / Observation 🔹 Logic: reversal length property 💡 Today’s takeaway: Not every problem needs heavy coding — sometimes the strongest solution comes from the right observation and choosing the correct algorithmic pattern. #DSA #Java #LeetCode #Codeforces #ProblemSolving #Algorithms #DataStructures #CodingInterview #SoftwareEngineer #100DaysOfCode Follow for more problem solving content and stay updated 🚀
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 Challenge – Day 130/360 🚀 📌 Topic: Backtracking / DFS on Grid 🧩 Problem: Word Search Problem Statement: Given a 2D grid of characters and a word, check if the word exists by moving in 4 directions (no cell reuse). 🔍 Example: Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]] word = "ABCCED" Output: true 💡 Approach: Backtracking + DFS 1️⃣ Step 1 – Start from every cell matching the first character 2️⃣ Step 2 – Explore 4 directions (up, down, left, right) recursively 3️⃣ Step 3 – Mark visited cells and backtrack after exploring ✔️ Avoid revisiting the same cell ✔️ Stop early when characters don’t match ✔️ Return true as soon as full word is found ⏱ Complexity: Time: O(N * M * 4^L) Space: O(L) (recursion stack) 📚 Key Learning: Backtracking is powerful for exploring all possible paths while avoiding invalid ones using pruning. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #130DaysOfCode #LeetCode #Backtracking
To view or add a comment, sign in
-
-
❌ I used to ignore Time & Space Complexity… Until my code started failing on large inputs. That’s when I realized: 👉 Writing code is easy 👉 Writing efficient code is what actually matters 🚀 Time & Space Complexity — Simplified ⏱️ Time Complexity (How fast your code runs) O(1) → Constant O(log n) → Binary Search O(n) → Linear traversal O(n log n) → Efficient sorting O(n²) → Nested loops O(2ⁿ) → Exponential (avoid if possible) 💾 Space Complexity (How much memory your code uses) O(1) → No extra memory O(n) → Extra storage O(n²) → Matrix O(2ⁿ) → Recursive explosion 🔥 Why it actually matters? ✔️ Your code should handle millions of inputs, not just 10 ✔️ Top companies test efficiency, not just correctness ✔️ Better complexity = faster + cheaper systems 🛠️ How I’m improving daily: ✅ Picking the right data structures ✅ Replacing brute force with optimized approaches ✅ Using Binary Search & Hashing wherever possible ✅ Practicing DSA problems consistently ✅ Analyzing time + space after every solution 🎯 Big lesson: 👉 Don’t just solve problems 👉 Solve them efficiently If you're learning DSA, remember: Small optimizations today → Big impact tomorrow 🚀 #DSA #Algorithms #CodingInterview #SoftwareEngineering #Java #LearningInPublic #100DaysOfCode #TechJou
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
-
🚀 DSA Journey — Day 17: Mastering Binary Search (LeetCode 704) Today I worked on one of the most fundamental and powerful algorithms in DSA — Binary Search. 🔍 Problem Understanding Given a sorted array, we need to efficiently find the index of a target element. If it exists, return its index; otherwise, return -1. 💡 Brute Force Approach Traverse the array linearly Compare each element with target Time Complexity: O(n) ⚠️ Not optimal for large datasets ⚡ Optimized Approach — Binary Search Since the array is sorted, we can eliminate half of the search space in every step. 👉 Steps: Initialize start = 0, end = n-1 Find middle: mid = (start + end) / 2 Compare: If nums[mid] == target → return index If target < mid → move left (end = mid - 1) If target > mid → move right (start = mid + 1) Repeat until found or search space ends 🧠 Example Walkthrough Array: [-1,0,3,5,9,12], Target: 9 mid = 2 → value = 3 → move right mid = 4 → value = 9 → ✅ Found ⏱️ Complexity Analysis Time Complexity: O(log n) Space Complexity: O(1) 🎯 Key Learning Binary Search is not just a problem — it's a pattern. Understanding this deeply will help in: Searching problems Optimization problems Many advanced DSA questions 🙏 Gratitude Grateful for the consistency and learning mindset every day 🙌 📈 Consistency is the real game changer. One problem a day = big results. #DSA #BinarySearch #LeetCode #CodingJourney #Java #ProblemSolving #Consistency #Learning #TechJourney #100DaysOfCode
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
-
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