Solved: Remove Duplicates from Sorted Array 🔍 Problem Summary: Given a sorted array, remove duplicates in-place such that each unique element appears only once and return the new length. 💡 Approach: ✔️ Used the Two Pointer technique ✔️ One pointer (index) tracks unique elements ✔️ Another pointer (j) scans the array ✔️ When a new element is found, move it forward 👨💻 Code (Java): public int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int index = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[index]) { index++; nums[index] = nums[j]; } } return index + 1; } ⚡ Key Learning: Understanding patterns is more important than memorizing solutions. Sorted array + duplicates → Two Pointer approach works efficiently. 📊 Complexity: ⏱ Time: O(n) 💾 Space: O(1) 📌 Improving step by step—consistency is the goal! #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Learning
Remove Duplicates from Sorted Array with Two Pointer Technique
More Relevant Posts
-
🔥 𝗗𝗮𝘆 𝟵𝟰/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟱𝟯𝟵. 𝗞𝘁𝗵 𝗠𝗶𝘀𝘀𝗶𝗻𝗴 𝗣𝗼𝘀𝗶𝘁𝗶𝘃𝗲 𝗡𝘂𝗺𝗯𝗲𝗿 | 🟢 Easy | Java Marked as Easy — but the optimal solution is pure binary search brilliance. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Given a sorted array, find the kth missing positive integer. Linear scan works — but can we do O(log n)? 💡 𝗧𝗵𝗲 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 At index i, the value arr[i] should be i+1 in a complete sequence. So missing numbers before arr[i] = arr[i] - 1 - i This lets us binary search on the count of missing numbers! ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵 ✅ If arr[mid] - 1 - mid < k → not enough missing numbers yet, go right ✅ Else → too many missing, go left ✅ After the loop, left + k gives the exact answer 𝗪𝗵𝘆 𝗹𝗲𝗳𝘁 + 𝗸? After binary search, left is the index where the kth missing number falls beyond. left numbers exist in the array before that point, so the answer is left + k. No extra passes needed. ✨ 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(log n) — vs O(n) linear scan 📦 Space: O(1) This is a perfect example of binary searching on a derived condition, not just a value. A real upgrade from the naive approach. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gVYcjNS6 𝟲 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗧𝗵𝗲 𝗳𝗶𝗻𝗶𝘀𝗵 𝗹𝗶𝗻𝗲 𝗶𝘀 𝗿𝗶𝗴𝗵𝘁 𝘁𝗵𝗲𝗿𝗲! 🏁 #LeetCode #Day94of100 #100DaysOfCode #Java #DSA #BinarySearch #Arrays #CodingChallenge #Programming
To view or add a comment, sign in
-
You can brute force this in O(n²)… or think smart and finish in O(n). Day 71 — LeetCode Progress Problem: Number of Good Pairs Required: Given an array nums, return the number of pairs (i, j) such that: i < j nums[i] == nums[j] Idea: Instead of checking all pairs, count frequency of each number. If a number appears c times, it can form: c × (c - 1) / 2 pairs. Approach: Use a HashMap to store frequency of each number Traverse the array and build frequency map For each frequency c: Add c * (c - 1) / 2 to result Return the result Time Complexity: O(n) Space Complexity: O(n) Small problem, but a powerful pattern: Counting + combinations = huge optimization. #LeetCode #DSA #Java #HashMap #ProblemSolving #CodingJourney” Day 71 — LeetCode Progress Problem: Number of Good Pairs Required: Given an array nums, return the number of pairs (i, j) such that: i < j nums[i] == nums[j] Idea: Instead of checking all pairs, count frequency of each number. If a number appears c times, it can form: c × (c - 1) / 2 pairs. Approach: Use a HashMap to store frequency of each number Traverse the array and build frequency map For each frequency c: Add c * (c - 1) / 2 to result Return the result Time Complexity: O(n) Space Complexity: O(n) Small problem, but a powerful pattern: Counting + combinations = huge optimization. #LeetCode #DSA #Java #HashMap #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Ever wondered what actually happens under the hood when you run a Java program? It’s not just magic; it’s the Java Virtual Machine (JVM) at work. Understanding JVM architecture is the first step toward moving from "writing code" to "optimizing performance." Here is a quick breakdown of the core components shown in the diagram: 1️⃣ Classloader System The entry point. It loads, links, and initializes the .class files. It ensures that all necessary dependencies are available before execution begins. 2️⃣ Runtime Data Areas (Memory Management) This is where the heavy lifting happens. The JVM divides memory into specific areas: Method/Class Area: Stores class-level data and static variables. Heap Area: The home for all objects. This is where Garbage Collection happens! Stack Area: Stores local variables and partial results for each thread. PC Registers: Keeps track of the address of the current instruction being executed. Native Method Stack: Handles instructions for native languages (like C/C++). 3️⃣ Execution Engine The brain of the operation. It reads the bytecode and executes it using: Interpreter: Reads bytecode line by line. JIT (Just-In-Time) Compiler: Compiles hot spots of code into native machine code for massive speed boosts. Garbage Collector (GC): Automatically manages memory by deleting unreferenced objects. 4️⃣ Native Interface & Libraries The bridge (JNI) that allows Java to interact with native OS libraries, making it incredibly versatile. 💡 Pro-Tip: If you are debugging OutOfMemoryError or StackOverflowError, knowing which memory area is failing is half the battle won. #Java #JVM #BackendDevelopment #SoftwareEngineering #ProgrammingTips #TechCommunity #JavaDeveloper #CodingLife
To view or add a comment, sign in
-
-
🔥 𝗗𝗮𝘆 𝟵𝟯/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟲𝟬𝟴. 𝗦𝗽𝗲𝗰𝗶𝗮𝗹 𝗔𝗿𝗿𝗮𝘆 𝗪𝗶𝘁𝗵 𝗫 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗧𝗵𝗮𝗻 𝗼𝗿 𝗘𝗾𝘂𝗮𝗹 𝗫 | 🟢 Easy | Java A self-referential condition — x elements must be ≥ x. Elegant problem, elegant solution. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Find x such that exactly x elements in the array are ≥ x. Return -1 if no such x exists. ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗙𝗿𝗲𝗾𝘂𝗲𝗻𝗰𝘆 𝗖𝗼𝘂𝗻𝘁 + 𝗦𝘂𝗳𝗳𝗶𝘅 𝗦𝘂𝗺 ✅ Cap all values at n (array length) — anything larger contributes the same way ✅ Build a frequency count array of size n+1 ✅ Traverse from right to left, accumulating a running suffix sum ✅ When suffix sum == current index i → x = i is the answer! 💡 𝗪𝗵𝘆 𝗰𝗮𝗽 𝗮𝘁 𝗻? x can never exceed n (can't have more elements than the array size). So values above n are equivalent — capping them avoids index overflow and keeps the logic clean. 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(n) — two passes 📦 Space: O(n) — frequency array No sorting. No binary search. Just a clever frequency count + suffix accumulation. Sometimes the cleanest approach is right under your nose. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gm2c4-6x 𝟳 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗦𝗼 𝗰𝗹𝗼𝘀𝗲 𝘁𝗼 𝟭𝟬𝟬! 💪 #LeetCode #Day93of100 #100DaysOfCode #Java #DSA #Arrays #FrequencyCount #CodingChallenge #Programming
To view or add a comment, sign in
-
Day 74 of #100DaysOfLeetCode 💻✅ Solved #162. Find Peak Element problem in Java. Approach: • Used Binary Search technique to efficiently find the peak element • Set two pointers, left at start and right at end of the array • Calculated mid index using safe mid formula • Compared nums[mid] with nums[mid + 1] to determine direction • If mid element is smaller, moved search space to right half • Otherwise, moved search space to left half including mid • Continued until left and right pointers converged • Final position (left == right) represents the peak index Performance: ✓ Runtime: 0 ms (Beats 100.00% submissions) 🚀 ✓ Memory: 44.32 MB (Beats 25.49% submissions) Key Learning: ✓ Strengthened understanding of Binary Search on unsorted arrays ✓ Learned how to apply divide-and-conquer beyond traditional searching ✓ Improved intuition for peak finding using neighbor comparison ✓ Practiced optimizing search space instead of linear scanning Learning one problem every single day 🚀 #Java #LeetCode #DSA #BinarySearch #Arrays #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Day 10.2 of Java with DSA Journey 🚀 📌 Problem: Base 7 Conversion (LeetCode 504) At first, this looks like a simple math problem… But it actually teaches something deeper: 👉 How numbers are built in different systems 💡 Core Idea To convert a number from base 10 → base 7: Divide by 7 Store remainder Repeat until 0 Reverse the result 🧠 Key Learnings 🔹 Understanding Number Systems Decimal (base 10) is just one system—this logic works for ANY base 🔹 Modulo + Division Pattern num % base → current digit num / base → move to next position 🔹 Why Reverse? We generate digits from least significant → most significant ⚡ Complexity ⏱ Time: O(log₇ n) 📦 Space: O(log₇ n) 🔥 Pro Tips (Interview Level) 💡 Tip 1: This is a Universal Pattern This exact logic works for: Binary (base 2) Octal (base 8) Hex (base 16) 👉 Learn once, apply everywhere. 💡 Tip 2: Handle Negatives Separately Always convert using abs(num) and attach - later This avoids tricky modulo behavior. 💡 Tip 3: Avoid String Concatenation in Loops Use StringBuilder 👉 Shows awareness of time complexity + memory efficiency 💡 Tip 4: Reverse Thinking = Interview Gold If you're building output backward → think reverse at the end 💡 Tip 5: Hidden Optimization Insight If allowed, you could also: Use recursion → cleaner logic Or pre-calculate size for optimization 🔥 Real Insight This problem is not about Base 7… It’s about understanding: 👉 How computers represent and transform numbers internally Once you master this, you can convert between any number systems. Consistency builds depth 📈 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #Algorithms #MathLogic #Day10 #BitManipulation #InterviewPrep #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Binary Tree Postorder Traversal (LeetCode 145) 💻 Language: Java 🔹 Approach: To solve this problem, I used Depth-First Search (DFS) with Recursion to perform postorder traversal of the binary tree. • Recursively traverse the left subtree • Recursively traverse the right subtree • Visit the root node and store its value • Follow Postorder pattern: Left → Right → Root This approach works efficiently because recursion naturally follows the postorder traversal structure. ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(n) (including recursion stack) 📖 Key Learning: This problem strengthened my understanding of DFS, recursion, and tree traversal patterns. It also reinforced the postorder pattern (Left → Right → Root), which is a fundamental concept used in many tree-based problems 💡 #DSA #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #BinaryTree #DFS #Recursion #TreeTraversal
To view or add a comment, sign in
-
-
Solved Find Peak Element -> LeetCode(162) Medium, Binary Search in Java. Till now I had solved around 10-11 binary search problems. But in all of them array was always sorted , even rotated ones had at least one sorted half. So I had one strong assumption , binary search only works on sorted arrays. This problem broke that assumption completely. No sorted half, no rotation logic working. I was stuck because none of my previous patterns were fitting here. Took help from Claude. It suggested slope based thinking , if right neighbour is greater, peak is on right side, go right. If left neighbour is greater, go left. If both neighbours are smaller, current element is peak. Then I questioned > what if slope breaks in between? Claude pointed me to re-read the problem. The key insight was that array has -∞ at both ends virtually, which guarantees at least one peak always exists. Applied my own logic from there and got it accepted Then Claude showed me a cleaner version , when low < high, at the point where low == high we already have our peak. No need for extra boundary checks. That gave me a second shorter solution. Also broke my second assumption > binary search doesn't always need while(low <= high). Sometimes while(low < high) is cleaner. Two wrong assumptions fixed in one problem 🙌 Took help but questioned it, understood it, then coded it myself. Github Repo link : https://lnkd.in/grF5ACw5 **Any other wrong assumption you had about binary search? Drop it below 👇** #DSA #Java #LeetCode #BinarySearch #LearningInPublic
To view or add a comment, sign in
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🚀 DAY 94/150 — CONNECTING TREE LEVELS! 🌳🔗 Day 94 of my 150 Days DSA Challenge in Java and today I solved a very interesting problem that focuses on level connections in Binary Trees 💻🧠 📌 Problem Solved: Populating Next Right Pointers in Each Node 📌 LeetCode: #116 📌 Difficulty: Medium 🔹 Problem Insight The task is to connect each node’s next pointer to its right node on the same level. If there is no right node → set next = null. 👉 This problem is based on a perfect binary tree, which allows some optimizations. 🔹 Approaches Used ✅ Approach 1: BFS (Level Order Traversal) • Use a queue to traverse level by level • Connect nodes within the same level using a prev pointer ✔️ Easy to understand ❌ Uses extra space (queue) ✅ Approach 2: Optimized (Constant Space) • Use already established next pointers • Connect: left → right right → next.left ✔️ No extra space (O(1)) ✔️ More optimized and elegant ⏱ Complexity Time Complexity: O(n) Space Complexity: • BFS → O(n) • Optimized → O(1) 🧠 What I Learned • Same problem can have multiple approaches (basic → optimized) • Perfect binary tree structure helps reduce complexity • Using existing pointers smartly can eliminate extra space 💡 Key Takeaway This problem taught me: How to connect nodes level-wise Difference between BFS vs pointer-based optimization Writing space-efficient solutions 🌱 Learning Insight Now I’m focusing more on: 👉 Moving from brute-force → optimized solutions 🚀 ✅ Day 94 completed 🚀 56 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gDWj7K5Q 💡 Optimization is about using what you already have. #DSAChallenge #Java #LeetCode #BinaryTree #BFS #DFS #Pointers #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
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
Amazing Work, And if you want to be any notes on any topic so please connect me.😊