🧠 Today I revisited a classic problem — removing duplicates from a sorted array in Java. It’s simple at first glance, but understanding why it works step by step really clarifies how two-pointer logic shines in array problems. How it works: j scans the array k marks where the next unique value goes When nums[j] ≠ nums[j-1], copy and move k forward Example: Input → [1,1,2,2,3] Output → k = 3, unique elements = [1,2,3] ✅ Time: O(n) ✅ Space: O(1) #Java #ProblemSolving #Algorithms #Coding #LeetCode
How to remove duplicates from a sorted array in Java
More Relevant Posts
-
Day 89 of #100DaysOfCode Solved Find Numbers with Even Number of Digits in Java 🔢 Approach The goal of this problem was to count how many integers in a given array have an even number of digits. I implemented two methods: findNumbers(int[] nums): This is the main function that iterates through every number in the input array nums. isEvenOrOdd(int n): This helper function takes an integer and determines if its digit count is even or odd. Inside the helper function, I used a while loop to count the digits: I initialized a count to 0. The loop continues as long as $n > 0$. In each iteration, I increment count and then perform integer division by 10 (n = n / 10) to remove the least significant digit. Finally, I return true if the total count of digits is even (count \% 2 == 0). This efficient, digit-by-digit checking approach resulted in a strong performance, beating 98.90% of other submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Array #ProblemSolving #Optimization
To view or add a comment, sign in
-
-
🔢 Today I worked on a classic matrix problem in Java — Diagonal Sum. The goal was simple: Calculate the sum of both the primary and secondary diagonals of a square matrix. Initially, I used a nested loop approach with O(n²) complexity. But then I optimized it to a clean O(n) solution by directly accessing diagonal indexes. While optimizing, I made an interesting mistake: ❌ I wrote if (i != matrix[i][matrix.length - 1 - i]) Here I accidentally compared an index with an element value. ✔ Correct approach: if (i != matrix.length - 1 - i) This ensures the center element in odd-sized matrices isn’t counted twice. 🧠 Key Learning: Indexes and values may look similar, but mixing them can break logic silently. Optimization is not just about speed — it’s about accuracy. #Java #leetcode #Coding #DSA #ProblemSolving #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 LeetCode Day--- 4 | “Median of Two Sorted Arrays” (Hard, Java) Today’s challenge was one of those that really test your logic, patience, and understanding of binary search. This problem wasn’t about just merging two sorted arrays — it was about thinking smarter 🧠. Instead of brute-forcing through both arrays (O(m+n)), I implemented a binary partition approach to achieve O(log(min(m, n))) efficiency 💡 What I learned today: Always choose the smaller array for binary search — it makes the partition logic simpler. Handle boundaries carefully with Integer.MIN_VALUE and Integer.MAX_VALUE. The goal is to find the perfect partition where: Left half ≤ Right half Elements are balanced across both arrays Once that’s done → median can be easily calculated! ✅ Result: Accepted | Runtime: 0 ms 🚀 Hard problem turned into a logic puzzle that was actually fun to solve! 🧩 Concepts Strengthened: Binary Search Partitioning Logic Edge Case Handling Mathematical Thinking #LeetCode #Day4 #Java #BinarySearch #ProblemSolving #CodingChallenge #DataStructures #Algorithms #CodeEveryday #DeveloperJourney #TechLearning #LeetCodeHard #CodingCommunity
To view or add a comment, sign in
-
-
Another late-night success Solved a tricky binary search + sliding window problem efficiently in Java, optimizing power distribution logic in minimal runtime. 📊 Runtime: 31 ms 💡 Beats 89.29% of Java submissions 🧩 Concepts used: Binary Search, Prefix Sum, Sliding Window Each accepted solution reminds me that writing clean, efficient code isn’t just about passing tests — it’s about thinking like the system itself. #Java #LeetCode #ProblemSolving #Algorithms #CodingJourney
To view or add a comment, sign in
-
-
📌 Day 16/100 - Reverse String (LeetCode 344) 🔹 Problem: Reverse a given string in-place — meaning you must modify the original array of characters without using extra space. 🔹 Approach: Used the two-pointer technique — one starting at the beginning and one at the end of the array. Swap characters at both pointers, then move them closer until they meet. Efficient, clean, and runs in linear time without additional memory allocation. 🔹 Key Learnings: In-place algorithms optimize space complexity significantly. The two-pointer pattern is a versatile tool for many array and string problems. Understanding mutable vs immutable structures in Java is crucial for memory efficiency. Sometimes, the simplest logic beats the most complex one. 🧠 “True efficiency lies in simplicity, not complexity.” #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #TwoPointers
To view or add a comment, sign in
-
-
Hii Connections 👋 Today I solved an interesting String problem in Java: Problem: Find the length of the longest substring without repeating characters. My Approach: I used the sliding window technique along with a Hashtable to track the last seen index of each character. Here’s the logic: Move a window through the string using two pointers (start and end). If a character repeats, move the start pointer just after the last occurrence of that character. Keep updating the maximum length (max) as the window expands. This approach efficiently solves the problem in O(n) time, avoiding unnecessary re-checks of characters. What I Learned: ✅ Sliding window works great for substring problems. ✅ Hashtable helps efficiently manage character indices. ✅ Optimization is often about tracking what you already know, not recalculating it. Another step forward in mastering DSA and pattern-based problem solving 💪 #Java #DSA #ProblemSolving #Coding #SlidingWindow #LeetCode #LearningEveryday
To view or add a comment, sign in
-
-
🚀 LeetCode Day 3: Reverse Integer Today’s challenge was all about reversing the digits of an integer while handling tricky edge cases — especially negative numbers and integer overflow. 🧠 💡 Problem: Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows, return 0. 🧩 Key Takeaways: Extract digits using modulo and division Manage negative numbers gracefully Check for overflow before building the reversed number 💻 Language: Java ✅ Topic: Math / Integer Manipulation Every day is a new step toward mastering problem-solving and improving coding logic. #LeetCode #100DaysOfCode #Java #CodingChallenge #ProblemSolving #LeetCodeJourney
To view or add a comment, sign in
-
-
Hii Connections 👋 I recently solved an interesting problem in Java: Problem: Count the number of pairs in an array that have a specific difference d. My Approach: I used the two-pointer technique for an optimized solution: Start with two pointers, left and right. Compare the difference between the elements at these pointers. If the difference < d, move right forward. If the difference == d, increment the count and move both pointers. If the difference > d, move left forward. This avoids unnecessary comparisons and runs in O(n) for a sorted array, unlike the brute-force O(n²) approach. What I Learned: ✅ Two-pointer technique is super powerful for array problems. ✅ Thinking in terms of patterns rather than brute force makes code efficient. ✅ Small optimizations can drastically improve performance. Sharing my journey and progress on DSA practice! #Java #DSA #Coding #ProblemSolving #TwoPointers #LeetCode #LearningEveryday #CodeNewbie
To view or add a comment, sign in
-
-
🧠 Total Grid Ways Problem — Recursive Approach in Java 💻 Exploring how to find all possible paths from the top-left corner to the bottom-right corner in a grid — moving only right or down. This recursive solution breaks the problem into smaller subproblems, combining their results to find total unique paths. ✨ Sometimes, even a simple grid teaches us how powerful recursion can be!
To view or add a comment, sign in
-
-
🚀 Day 26 of 100 Days of LeetCode 📘 Problem: Search a 2D Matrix 💻 Language: Java ✅ Status: Accepted — Runtime: ⚡ 0 ms (Beats 100%) Today’s problem focused on searching efficiently within a 2D matrix — a great exercise for understanding nested loops, traversal logic, and time optimization. While this version used a simple brute-force approach, it served as a good refresher on matrix iteration patterns before moving on to more optimized binary search techniques in 2D grids. ✨ Key Learnings: Matrix traversal can be intuitive when visualized 🔢 Always consider both brute-force and optimized approaches — understanding both is key to depth of knowledge Writing clean, readable code matters as much as optimizing it Each problem solved is another small brick in the foundation of strong problem-solving skills 💪 #Day26 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #SoftwareDevelopment #Matrix #KeepLearning #CodeEveryday
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