Problem 25 : Leetcode 🚀 LeetCode Problem Solved: Find the Duplicate Number (Cyclic Sort Approach) 🧠 🔍 Problem Overview: Given an array of n+1 integers where each number is between 1 and n (inclusive), at least one duplicate number must exist. The task: Find that duplicate — with O(n) time and O(1) extra space. 💡 My Approach – Cyclic Sort Technique: I applied the Cyclic Sort algorithm to achieve both performance and space efficiency. In-Place Hashing Logic: I treated the array as a hash map where each number x should ideally be placed at index x - 1. Duplicate Detection: If arr[i] != arr[arr[i] - 1], I swapped the elements to place them correctly. If arr[i] == arr[arr[i] - 1], it indicates that arr[i] is the duplicate number — and I immediately returned it. 🏁 Results: ✅ Time Complexity: O(n) – Runtime: 6 ms, beating 50.29% of Java submissions. ✅ Space Complexity: O(1) – Solved entirely in-place. ✅ Memory Usage: 82.82 MB, outperforming 6.05% of other submissions. 🧩 Tech Insight: Cyclic Sort is an elegant in-place sorting strategy ideal for problems involving numbers within a fixed range — making it a powerful tool for efficient duplicate detection and data placement. #LeetCode #Java #DSA #ProblemSolving #CodingJourney #SpringBootDeveloper #BackendDevelopment #CyclicSort #JavaDeveloper #LearningInPublic Link : https://lnkd.in/diWSfAaM
Solved LeetCode Problem 25 with Cyclic Sort in Java
More Relevant Posts
-
Problem 26 : LeetCode 🚀 LeetCode Medium Solved: Find All Duplicates in an Array (Cyclic Sort Approach) 🧩 I just tackled another LeetCode Medium challenge — this one tested both my problem-solving and in-place algorithm design skills. 🔍 Problem Overview: Given an array of integers where each value is between 1 and n, the goal was to find all duplicate numbers — with O(n) time and O(1) extra space. 💡 My Approach – Cyclic Sort Logic: I used the Cyclic Sort algorithm, which treats the array itself like a hash map. Each element x should be at index x - 1. During the sorting process: If the element is not in the right place → swap it. If a duplicate is detected (arr[i] == arr[arr[i]-1]) → record it. This approach avoids using any extra data structure for indexing and works entirely in-place. ⚙️ Results: ✅ Runtime: 14 ms → Beats 42.80% of Java submissions ✅ Memory: 59.84 MB → Beats 8.98% of submissions ✅ Complexity: O(n) time | O(1) space ✅ Status: Accepted 🎉 (All 29 test cases passed) 📚 Tech Stack Used: Java | Cyclic Sort | HashSet | Array Manipulation | DSA Every solved problem strengthens logic, debugging, and clarity of thinking — a step closer to writing efficient production-grade code. #LeetCode #Java #ProblemSolving #CyclicSort #DataStructures #Algorithms #BackendDeveloper #SpringBoot #LearningInPublic #CodeJourney Question Url : https://lnkd.in/dwz6UWyH
To view or add a comment, sign in
-
-
Problem 27 : LeetCode 🎯 LeetCode Problem #645 Solved — Set Mismatch (Cyclic Sort Approach) 🧩 Today, I solved another interesting LeetCode Easy problem — “Set Mismatch”, which deepened my understanding of in-place sorting and index mapping using the Cyclic Sort technique. 🔍 Problem Overview Given an integer array nums where numbers are supposed to be from 1 to n, one number is duplicated, and one number is missing. The task: Find both numbers using O(n) time and O(1) space. 💡 My Approach — Cyclic Sort Technique I treated the array like a self-mapping structure where each number x should ideally be placed at index x - 1. If the current element isn’t in its correct place and its target isn’t already filled, I swap it. After the array is sorted in place, any index i where arr[i] != i + 1 indicates: arr[i] → the duplicate number i + 1 → the missing number ⚙️ Results ✅ Runtime: 3 ms — Beats 79.76% of Java submissions ✅ Memory: 47.45 MB — Beats 6.28% of submissions ✅ Complexity: O(n) time | O(1) space ✅ Status: Accepted ✅ (All 49 test cases passed) 🧩 Tech Stack Java | Cyclic Sort | Array Manipulation | In-Place Algorithm | DSA Another problem that reinforces my confidence in index-based logic and memory-efficient coding patterns — vital skills for backend and system optimization. #LeetCode #Java #ProblemSolving #CyclicSort #DataStructures #Algorithms #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Question Url : https://lnkd.in/dixwjFE3
To view or add a comment, sign in
-
-
🚀 Day 146 / 180 of #180DaysOfCode ✅ Today’s Highlight: Revisited LeetCode 3234 — “Count the Number of Substrings With Dominant Ones.” 🧩 Problem Summary: Given a binary string s, the task is to count how many of its substrings have dominant ones. A substring is considered dominant if: number of 1s ≥ (number of 0s)² This creates an interesting balance check between zeros and ones, pushing you to think about substring ranges, prefix behavior, and efficient counting techniques. 💡 Core Takeaways: Great exercise in string analysis and prefix-based reasoning Highlights how mathematical conditions influence algorithm design Reinforces handling frequency relationships inside a sliding or expanding window Efficient counting becomes essential due to potential O(n²) substrings 💻 Tech Stack: Java ⏱ Runtime: 115 ms (Beats 84.11%) 💾 Memory: 47 MB 🧠 Learnings: Strengthened understanding of substring behavior under unique constraints Refined thinking around optimizing brute-force patterns A good reminder of how theoretical conditions (like squaring zeros) change practical implementation choices 📈 Progress: Today’s problem significantly improved my intuition around constraint-based substring evaluation—valuable for more advanced algorithmic challenges ahead. #LeetCode #Java #Algorithms #SubstringProblems #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #180DaysOfCode #LogicBuilding #LearningEveryday
To view or add a comment, sign in
-
-
💡 LeetCode 1929 – Concatenation of Array 💡 Today, I solved LeetCode Problem #1929: Concatenation of Array, a simple yet satisfying problem that tests your understanding of array manipulation and indexing in Java. ⚙️📊 🧩 Problem Overview: You’re given an integer array nums. Your task is to create a new array ans such that ans = nums + nums (i.e., concatenate the array with itself). 👉 Example: Input → nums = [1,2,1] Output → [1,2,1,1,2,1] 💡 Approach: 1️⃣ Find the length n of the given array. 2️⃣ Create a new array of size 2 * n. 3️⃣ Loop through nums once — place each element both at index i and index n + i. 4️⃣ Return the resulting array. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the array. ✅ Space Complexity: O(n) — For the concatenated array. ✨ Key Takeaways: Practiced index manipulation and array construction. Reinforced the importance of efficient iteration. A great warm-up problem that strengthens logical thinking and array fundamentals. 🌱 Reflection: Even the simplest problems build the foundation for solving more complex ones. Every bit of consistent practice helps in mastering problem-solving and clean coding habits. 🚀 #LeetCode #1929 #Java #ArrayManipulation #DSA #CodingJourney #CleanCode #ProblemSolving #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
📌 Day 10 of #45DaysOfLeetCode Challenge – Problem 2: Add Two Numbers (Medium)🚀 🔹Today’s problem tested my understanding of Linked Lists and carry-over logic in addition operations. 🔹The task was to add two numbers represented as linked lists where each node contains a single digit in reverse order — a neat way to simulate how we perform addition by hand! 🧠 Key Learnings: 🔹Handling edge cases when list lengths differ. 🔹Managing carry efficiently between node sums. 🔹Constructing a new linked list to store the result dynamically. 🔹Using a dummy head node to simplify list manipulation. 🚀 My solution achieved: ✅ Runtime: 1 ms (Beats 100%) ✅ Status: Accepted ✅ Language: Java 🔹This challenge reminded me that clarity in logic matters more than complex code — a small trick like using a dummy node can make your entire implementation cleaner and bug-free.🚀 🔗 Problem : https://lnkd.in/dCnS8iAh 😎 #Day10 #LeetCode #CodingChallenge #JavaDeveloper #DataStructures #LinkedList #ProblemSolving #CodeEveryday #100DaysOfCode
To view or add a comment, sign in
-
-
I solved LeetCode 42: Trapping Rain Water in Java, and it turned out to be one of those problems that looks straightforward at first but hides deep lessons in algorithm design and optimization. The problem asks you to calculate how much water can be trapped between bars of different heights after it rains. It sounds simple, but when you try to implement it, you realize how easily brute-force approaches break down. My initial solution used nested loops to check how much water could be trapped at every index. It worked but ran with O(n²) time complexity, which quickly became inefficient for large inputs. That is when I shifted toward precomputation. The key idea is to figure out how much water each bar can hold by knowing the tallest bar to its left and right. Once that information is known, the amount of trapped water at any position is simply the minimum of those two maximum heights minus the height of the bar itself. To make this efficient, I created two arrays: maxLeft[i] stores the tallest bar to the left of index i. maxRight[i] stores the tallest bar to the right of index i. This approach brought the time complexity down to O(n) while keeping the logic simple and elegant. This problem taught me that performance improvements often come from rethinking the way you process information. Precomputation, caching, and avoiding repetitive operations are not just algorithmic tricks. They are the same concepts that drive efficiency in backend engineering, database optimization, and system design. In many ways, this problem reflects real-world engineering. It is not about how fast you can write code, but how effectively you can anticipate what the system will need before it needs it. That mindset is what separates good developers from great ones. What is one problem that helped you truly understand the balance between simplicity and optimization? #Java #Programming #SoftwareDevelopment #ProblemSolving #Algorithms #Coding #DSA #LeetCode #Engineering #SystemDesign
To view or add a comment, sign in
-
-
💻 Enhancing Problem-Solving Skills with LeetCode (Java) Recently solved a couple of fundamental algorithmic problems that helped strengthen my understanding of two-pointer techniques, array manipulation, and writing efficient solutions. 🔹 Container With Most Water Implemented an optimised two-pointer approach to find the maximum water area between vertical lines. Instead of checking every pair (which would be O(n²)), the solution smartly moves the pointer at the shorter height inward to explore potentially larger areas. Approach: Two Pointers, Greedy Time Complexity: O(n) Space Complexity: O(1) 🔹 3Sum Solved the classic triplet-finding challenge by sorting the array and using two pointers to efficiently search for combinations that sum to zero. Also handled duplicates to avoid repeated triplets. Approach: Sorting + Two Pointers Time Complexity: O(n²) Space Complexity: O(1) (excluding output list) These problems helped sharpen my understanding of pointer movement, edge-case management, and designing clean, efficient solutions. #LeetCode #Java #Algorithms #DSA #Coding #ProblemSolving #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
🤯 Controversial Take: The Private Field is a Lie, and It's Killing Your Tests. 🧪 If you are a serious C# or Java developer, you were taught to use the private keyword for encapsulation—to hide data and protect the internal state of a class. But here is the brutal truth that separates textbook code from real-world, highly testable code: Blind adherence to private fields is an anti-pattern. The Encapsulation Misinterpretation 🔒 Encapsulation's goal is to protect the object's invariants (its rules and structural integrity), not to hide every single piece of data from the rest of the application. When you make a field private, you gain nothing but pain when it comes time for unit testing: 1. Test Fragility: You are forced to test the internal state by only interacting with public methods. If those public methods are complex, your tests become complex and brittle. 2. Unnecessary Complexity: Developers create awkward, unnecessary public methods (SetInternalStateForTesting()) or use reflection (a hack!) just to check a private field's value after an action. 3. No Isolation: Your test is no longer a simple unit test; it becomes an integration test because you have to run through the entire public API to observe a single internal change. The "Testable" Alternative: Internal or Protected 💡 For logic that must be tested but shouldn't be exposed to the public API of the assembly, internal (or protected for inheritance) is often the superior choice. By exposing fields to your separate Test Assembly (using InternalsVisibleTo in C#), you enable: • Atomic Unit Tests: You can directly assert that a single action correctly modified a single internal field, making your tests precise, fast, and stable. • Faster Development Cycle: You waste zero time writing wrapper methods solely for testing purposes. The GC is your best friend, but you have to write code that allows it to work efficiently. Poorly managed references are the single biggest bottleneck that modern garbage-collected languages face. Agree or Disagree? Is the textbook definition of private ruining developer productivity, or is exposing internal fields a reckless path to chaos? Let the debate begin. 👇 #OOP #Csharp #Java #UnitTesting #CleanCode #SoftwareArchitecture
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