#Coding10 👉 Q: Remove Duplicates from a Sorted Array (Two Pointer Technique – Java). Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 ✅ Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; // pointer for next unique position for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j] = arr[i]; j++; } } return j; // number of unique elements } How It Works Since the array is already sorted, duplicates are adjacent i scans the array j tracks the position to place the next unique element When a new element is found → place it at index j Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) Two-pointer pattern is extremely powerful for array problems. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
Remove Duplicates from Sorted Array in Java using Two Pointer Technique
More Relevant Posts
-
----Continuing my DSA practice using Java.---- Today I solved “Isomorphic Strings.” Two strings are isomorphic if characters in one string can be replaced to get the other, while maintaining a consistent one-to-one mapping. Instead of using HashMaps, I used two fixed-size arrays to track character mappings in both directions. If the mapping didn’t match at any index, the strings were not isomorphic. Key takeaway: When character constraints are small (like ASCII), arrays can be faster and cleaner than HashMaps. #DSA #Java #Strings #ProblemSolving #LearningJourney
To view or add a comment, sign in
-
-
#Coding9 Q: Move Zeros to the End (Two Pointer Technique – Java) Example: int[] arr = {0, 1, 0, 3, 12}; Output → {1, 3, 12, 0, 0} ✅ Two Pointer Technique (Optimal – O(n), O(1)) static void moveZeros(int[] arr) { int j = 0; // position to place next non-zero for(int i = 0; i < arr.length; i++) { if(arr[i] != 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j++; } } } How It Works i scans the entire array j tracks where the next non-zero should go When a non-zero is found → swap with index j Zeros automatically move toward the end Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) This approach is interview-preferred because it is efficient and preserves order. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
Solved the classic Binary Tree traversal problem using recursion in Java. 🔎 Approach: Inorder follows the pattern: Left → Root → Right ✔️ If the node is null, return (base case) ✔️ Recursively traverse the left subtree ✔️ Add the current node’s value to the result list ✔️ Recursively traverse the right subtree This traversal is especially important because in a Binary Search Tree (BST), inorder traversal gives elements in sorted order. ⏱️ Runtime: 0 ms Understanding recursion + tree traversal patterns makes so many tree problems easier to approach.
To view or add a comment, sign in
-
-
🚀 Day 5/30 – Java DSA Challenge 🔎 Problem 41: 209. Minimum Size Subarray Sum (LeetCode – Medium) Another powerful Sliding Window (Variable Size) problem 🔥 🧠 Problem Summary Given: An array of positive integers A target value 🎯 Return the minimum length of a contiguous subarray whose sum ≥ target. If no such subarray exists → return 0. 💡 Key Insight Since all numbers are positive, we can safely use: ✅ Variable Sliding Window Why? Because: Expanding window → sum increases Shrinking window → sum decreases No negative values to break logic 🔄 Approach 1) Expand right pointer → keep adding to sum 2) When sum ≥ target → -Update minimum length -Shrink from left to find smaller valid window 3) Continue until end ⏱ Time Complexity ✅ O(n) Each element is added and removed at most once. 📦 Space Complexity ✅ O(1) No extra data structures used. 🎯 Pattern Name Variable Size Sliding Window Minimum Window with Condition Shrink When Valid Pattern 🔥 41 Problems Completed Day 5 = Full Sliding Window Mastery 💪 Today covered: At most K distinct Fixed window Variable window Frequency matching Minimum window condition Serious progress 🚀 #Day5 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #TwoPointers #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
DSA Practice – Bubble Sort Implementation in Java :- What is Bubble Sort ? Bubble Sort is a simple comparison-based sorting algorithm where adjacent elements are compared and swapped if they are in the wrong order. This process repeats until the array becomes sorted. How It Works: Traverse the array multiple times Compare adjacent elements Swap them if they are in the wrong order After each iteration, the largest element “bubbles up” to its correct position #JAVA #DSA
To view or add a comment, sign in
-
-
🚀 Day 6/30 – Java DSA Challenge 🔎 Problem 44: 992. Subarrays with K Different Integers (LeetCode – Hard) Today’s problem is a Hard-level extension of the sliding window counting pattern 🔥 🧠 Problem Summary Given an integer array nums and an integer k, 🎯 Return the number of subarrays that contain exactly k distinct integers. A subarray must be contiguous. 💡 Key Insight Counting exactly k distinct elements directly is difficult. So we use the powerful trick: ✅ Exactly(K) = AtMost(K) − AtMost(K − 1) This converts a Hard problem into two manageable sliding window problems. 🔄 Approach 1️⃣ Write a helper function atmost(k) → Count subarrays with at most k distinct elements 2️⃣ Use Sliding Window + HashMap: Expand right pointer Store frequency of elements If distinct count exceeds k, shrink from left Add (window size) to answer 3️⃣ Final Answer: atMost(k) − atMost(k − 1) ⏱ Time Complexity O(n) – Each element enters and leaves window once 📦 Space Complexity O(k) – HashMap stores at most k distinct elements 📌 Pattern Mastered ✔ Sliding Window – Variable Size ✔ HashMap Frequency Tracking ✔ Subarray Counting Pattern ✔ Exactly K = AtMost(K) − AtMost(K − 1) 🔥 Sliding Window Evolution So Far Minimum window length Fixed size window Binary subarrays with sum Nice subarrays (odd count) Subarrays with K distinct integers Now the pattern recognition is becoming automatic 💪 🔥 44 Problems Completed Day 6 = Hard-level Sliding Window conquered 🚀 #Day6 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #HashMap #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
To view or add a comment, sign in
-
-
🚀 Day 6/30 – Java DSA Challenge 🔎 Problem 43: 930. Binary Subarrays With Sum (LeetCode – Medium) Today I solved another important Sliding Window + Counting pattern problem 🔥 🧠 Problem Summary Given a binary array nums (only 0s and 1s) and an integer goal, 🎯 Return the number of non-empty subarrays whose sum equals goal. 💡 Key Insight Since the array contains only 0s and 1s, Sum of subarray = Number of 1s in that subarray. So the problem becomes: Count subarrays with exactly goal number of 1s. 🔥 Core Trick Used Instead of directly counting exactly goal, we use: ✅ Exactly(K) = AtMost(K) − AtMost(K − 1) This is a powerful sliding window counting pattern. 🔄 Approach 1️⃣ Write a helper function atmost(k) → Count subarrays with at most k ones 2️⃣ Use sliding window: Expand right pointer If count of 1s exceeds k, shrink from left Add (window size) to answer 3️⃣ Final Answer: atMost(goal) − atMost(goal − 1) ⏱ Time Complexity O(n) – Each element is processed at most twice 📦 Space Complexity O(1) – Constant extra space 📌 Pattern Learned ✔ Subarray Counting Pattern ✔ Sliding Window – Variable Size ✔ Exactly K = AtMost(K) − AtMost(K − 1) ✔ Binary array optimization 🔥 43 Problems Completed Day 6 = Strong grip on subarray counting patterns The more I practice Sliding Window, the clearer the patterns become 💪🚀 #Day6 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 3/30 – Java DSA Challenge 🔎 Problem 23: 766. Toeplitz Matrix (LeetCode – Easy) Today’s problem was based on matrix traversal and diagonal checking 🔥 🧠 Problem Statement A matrix is called Toeplitz if every diagonal from top-left to bottom-right contains the same elements. Return true if the matrix is Toeplitz, otherwise false. 💡 Example Input: [[1,2,3,4], [5,1,2,3], [9,5,1,2]] Output: true ✅ Because every diagonal has identical elements. 💡 Approach Used Key observation 👇 If a matrix is Toeplitz, then: matrix[i][j] == matrix[i-1][j-1] for all valid i and j. ✔ Start from index (1,1) ✔ Compare each element with its top-left neighbor ✔ If mismatch found → return false ✔ If loop completes → return true ⏱ Time Complexity: O(m × n) 📦 Space Complexity: O(1) 📌 Key Learning Practiced 2D matrix traversal Understood diagonal relationship logic Learned how small observations simplify matrix problems 23 Problems Completed 🔥 Day 3 consistency is building strong logic 💪🚀 #Day3 #30DaysOfCode #Java #DSA #LeetCode #Matrix #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 8/30 – Java DSA Challenge 🔎 Problem 49: 35. Search Insert Position (LeetCode – Easy) Today I solved a classic Binary Search variation 🔥 🧠 Problem Summary Given: A sorted array of distinct integers A target value 🎯 Return: The index if target exists Otherwise, the index where it should be inserted ⚠️ Required Time Complexity → O(log n) 💡 Key Insight This is not just searching. It’s about finding the correct insert position while maintaining sorted order. 👉 If target is not found, the low pointer after binary search will automatically point to the correct insert index. 🔄 Correct Approach We modify standard binary search slightly: If nums[mid] == target → return mid If nums[mid] < target → search right Else → search left If loop ends → return low ⏱ Time Complexity O(log n) 📦 Space Complexity O(1) 📌 Pattern Learned ✔ Binary Search ✔ Lower Bound Concept ✔ Insert Position Logic ✔ Search in Sorted Array 🎯 Important Note Your previous code returns -1 if not found. But for this problem, we must return low instead of -1. That small modification makes it a different problem 💡 🔥 49 Problems Completed Day 8 = Binary Search variations practice Mastering Binary Search opens doors to: First/Last occurrence Lower/Upper bound Rotated arrays Search on answer problems 🚀 #Day8 #30DaysOfCode #Java #DSA #LeetCode #BinarySearch #InterviewPrep #ProblemSolving #Consistency
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