🧩 Question: “Remove all duplicates such that each element appears only once.” (This is similar to your previous one but helps you understand pointer movement better.) 📝 Problem Statement (in simple words): You are given a sorted array, like nums = [1, 1, 2, 2, 3, 4, 4] You need to modify the array in place (without using extra space) so that each unique element appears only once. And finally, return the count of unique elements. After processing, your array should look like: [1, 2, 3, 4, ...] and your function should return 4. ⚙️ How to Think — Using Two Pointers: Let’s name the two pointers: i → the “slow” pointer (starts at index 0) j → the “fast” pointer (starts at index 1) Idea: We compare nums[i] and nums[j]. If both are same, it means duplicate — move j forward to skip it. If they are different, that means nums[j] is a new unique number. Move i forward by one (i++) Copy nums[j] to nums[i] Then move j forward again Keep doing this until j reaches the end of the array. #DSA #TwoPointer #Java #CodingJourney #LearningInPublic #ProblemSolving #ProgrammerLife #MERNDeveloper #LeetCode #CodeNewbie #TechLearning #SoftwareEngineering #100DaysOfCode
How to remove duplicates from a sorted array using two pointers.
More Relevant Posts
-
✅ Day 64 of LeetCode Medium/Hard Edition Today’s challenge was “Minimum Flips to Make a Binary String Monotone Increasing” — a brilliant mix of Dynamic Programming and binary state transitions 💡💻 📦 Problem: A binary string is monotone increasing if it consists of some number of 0s (possibly none) followed by some number of 1s (possibly none). We can flip any bit (0 → 1 or 1 → 0). Return the minimum number of flips required to make the string monotone increasing. 🔗 Problem Link: https://lnkd.in/grfy-BmC ✅ My Submission: https://lnkd.in/gKqQMxFG 💡 Thought Process: This problem can be visualized as maintaining two phases in the string — a sequence of 0s followed by a sequence of 1s. At each position, we decide whether to flip the current bit or transition to the next phase. We use recursion + memoization to find the minimal number of flips. Steps: 1️⃣ Define a recursive function helper(idx, bit) where bit represents the current phase (0-phase or 1-phase). 2️⃣ For each character: • If in 0-phase and current bit is '1', either flip it to '0' or transition to 1-phase. • If in 1-phase and current bit is '0', you must flip it to '1'. 3️⃣ Memoize results in dp[idx][bit] to avoid recomputation. 4️⃣ Return the minimal flips from start to end. ⚙️ Complexity: ⏱ Time: O(n × 2) — two states per index 💾 Space: O(n × 2) — due to memoization #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #ProblemSolving #Java #CodingChallenge
To view or add a comment, sign in
-
-
📌 Day 3/100 - Remove Duplicates from Sorted Array (LeetCode 26) 🔹 Problem: Given a sorted array, remove the duplicates in-place so that each element appears only once and return the new length. You must modify the array without using extra space for another array. 🔹 Approach: I used a simple counting-based approach: Iterate through the array using a single loop. If the current element is the same as the next, skip it. Otherwise, place it at the current count index and increment count. Finally, return count as the number of unique elements. 🔹 Key Learning: Practiced in-place array modification efficiently without extra space. Improved understanding of loop-based filtering logic. Realized that sometimes the simplest linear approach works best! Consistency compounds — each problem adds a new layer of confidence! 🚀#100DaysOfCode #LeetCode #Java #ProblemSolving #Array #DSA #TwoPointers
To view or add a comment, sign in
-
-
💡 LeetCode #15 — 3Sum Today I solved LeetCode Problem 15: 3Sum 🔍 Problem Summary: Given an integer array nums, return all unique triplets (a, b, c) such that: a + b + c = 0 The solution must not contain duplicate triplets. Key Idea: Use sorting + two pointers to reduce the time from O(n³) to O(n²). Steps: Sort the array. Fix one number (nums[f]) in each iteration. Use two pointers (i and j) to find pairs whose sum equals -nums[f]. Skip duplicates for both the fixed index and the pointer values. This efficiently finds all unique triplets. #LeetCode #Java #DSA #TwoPointers #ProblemSolving #CodingChallenge #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 31: LeetCode 167 — Two Sum II (Two Pointer Approach) 🔹 Concept Covered: Two Pointer Technique on a Sorted Array 🔹 Problem Goal: Find two numbers such that they add up to a specific target. 🔹 Approach: Use two pointers (low at start, high at end). Calculate the sum of both pointers. If sum == target → return indices. If sum > target → move high-- (reduce sum). If sum < target → move low++ (increase sum). 💡 Time Complexity: O(n) 💡 Space Complexity: O(1) 🎯 Learning: The two-pointer approach is extremely efficient for sorted arrays — no need for nested loops or hash maps. It’s all about moving intelligently in one pass! #LeetCode #Day31 #TwoPointer #Java #CodingJourney #YeswanthCodes
To view or add a comment, sign in
-
-
📌 Day 2/100 – Remove Element (LeetCode 27) 🔹 Problem: Given an integer array nums and a value val, remove all instances of that value in-place and return the new length of the array. The order of elements can be changed. 🔹 Approach: Used the two-pointer technique to efficiently modify the array in-place. One pointer iterates through the array, while the other tracks the position to overwrite non-val elements. Returned the position of the second pointer as the new length. 🔹 Key Learning: Strengthened understanding of in-place array manipulation. Improved logic building for pointer movement and conditional overwriting. Learned how to minimize extra space usage while maintaining readability and clarity. Another small yet powerful step toward mastering array-based problems! 💻 🔥 #100DaysOfCode #LeetCode #Java #ProblemSolving #TwoPointers #DSA #CodingJourney
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 67 Reverse Words in a String Problem: – Reverse Words in a String Task: – Given a string, reverse the order of the words and remove extra spaces. Example: Input: s = " the sky is blue " → Output: "blue is sky the" My Approach: Used trim() to remove leading and trailing spaces. Split the string using split("\\s+") to handle multiple spaces. Reversed the array and joined the words with a single space. Time Complexity: O(N) | Space Complexity: O(N) Even simple string problems can teach the importance of clean code and efficient use of built-in methods. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #GeeksForGeeks #CodeNewbie #StringManipulation
To view or add a comment, sign in
-
-
💻 Day 74 of #LeetCode100DaysChallenge Solved LeetCode 18: 4Sum — a challenging problem that enhances array manipulation, two-pointer technique, and handling duplicates. 🧩 Problem: Given an array nums of n integers and a target value, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: All indices are distinct The sum of the four numbers equals the target Result can be returned in any order 💡 Approach — Sorting + Two Pointers: 1️⃣ Sort the array to simplify duplicate handling. 2️⃣ Use two nested loops to fix the first two numbers. 3️⃣ Apply the two-pointer technique for the remaining two numbers to find quadruplets that sum to the target. 4️⃣ Skip duplicate elements to ensure uniqueness. 5️⃣ Collect all valid quadruplets in a list. ⚙️ Complexity: Time: O(N³) — two loops + two-pointer scan Space: O(N) — for storing results ✨ Key Takeaways: ✅ Strengthened two-pointer technique for k-sum problems. ✅ Learned efficient strategies for avoiding duplicates in combinatorial results. ✅ Practiced breaking down complex problems into smaller, manageable steps. #LeetCode #100DaysOfCode #Java #TwoPointers #Arrays #4Sum #DSA #ProblemSolving #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
💡 LeetCode #167 — Two Sum II (Input Array Is Sorted) Today I solved LeetCode Problem 167: Two Sum II — Input Array Is Sorted 🎯 Problem Summary: You are given a sorted array and a target. Return the 1-indexed positions of the two numbers that add up to the target. You must use O(1) extra space. Key Idea: Use the two-pointer technique 👈👉 Start with one pointer at the beginning (left) and one at the end (right). If the sum is too large → move right leftward. If the sum is too small → move left rightward. Stop when you find the pair. This works because the array is already sorted. #LeetCode #Java #DSA #TwoPointers #Algorithms #ProblemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🔹 Day 46: Is Subsequence (LeetCode #392) 📌 Problem Statement: Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence is formed by deleting some (possibly none) characters from the original string without disturbing the relative order of the remaining characters. ✅ My Approach: I used a two-pointer technique — one pointer iterates through string t, and the other tracks progress through string s. Each time a matching character is found, the pointer for s moves forward. If we reach the end of s, it means all its characters appeared in sequence within t. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 2 ms (Beats 68.53%) Memory: 41.32 MB (Beats 87.28%) 💡 Reflection: A simple yet elegant problem that highlights how pointer movement can efficiently handle string comparisons without extra memory usage. ✨ #LeetCode #Java #Strings #TwoPointers #100DaysOfCode #Day46
To view or add a comment, sign in
-
-
28/30days✅ #2427 Number of Common Factors The logic behind the Number of Common Factors problem is simple yet efficient. The goal is to find how many numbers can divide both given integers a and b without leaving a remainder. To achieve this, I first identify the smaller of the two numbers using Math.min(a, b) since no common factor can be greater than the smaller value. Then, I use a loop that runs from 1 up to that number and check for each value whether it divides both a and b completely (a % i == 0 && b % i == 0). If it does, it’s counted as a common factor. Finally, the program returns the total count of such numbers. For example, if a = 12 and b = 6, the common factors are 1, 2, 3, and 6, giving the output 4. This approach is easy to implement, logically clear, and works efficiently for all valid inputs. #LeetCode #Java #Coding #ProblemSolving
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