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
Solved LeetCode 645: Set Mismatch 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 24 : LeetCode 🚀 LeetCod Solved — Problem #448: Find All Numbers Disappeared in an Array (Cyclic Sort Approach) 🧩 Today, I explored another elegant application of the Cyclic Sort algorithm — solving the classic “Find All Numbers Disappeared in an Array” problem from LeetCode. 🔍 Problem Overview Given an array of integers where 1 ≤ a[i] ≤ n (with n being the array size), some elements appear twice while others appear once. The task: Find all numbers that do not appear in the array, with ⏱️ O(n) runtime 🧠 O(1) extra space 💡 My Approach — Cyclic Sort in Action I used Cyclic Sort for an in-place, efficient solution: In-Place Placement: Each number x should ideally be placed at index x - 1. During iteration, if arr[i] isn’t in its correct position and its target spot isn’t already occupied, I swap the two elements. Missing Number Detection: After sorting, I perform a linear scan — for every index i where arr[i] != i + 1, the missing number is i + 1. ⚙️ Results ✅ Time Complexity: O(n) — Runtime 7 ms, beating 47.63% of Java submissions ✅ Space Complexity: O(1) — Achieved true in-place solution (no extra data structures) ✅ Memory: 67.09 MB — beating 5.95% of submissions 🧩 Tech Stack: Java | Cyclic Sort | Array Manipulation | In-Place Algorithms | DSA Every such problem reinforces my understanding of data placement logic, index manipulation, and memory efficiency — skills essential for writing optimized backend and system-level code. #LeetCode #Java #ProblemSolving #DataStructures #Algorithms #CyclicSort #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Link : https://lnkd.in/d4Z8zTE4
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
-
-
Day 27 of #100DaysOfCode – LeetCode Problem #496: Next Greater Element I 🧩 Problem: Given two arrays nums1 and nums2, where nums1 is a subset of nums2, find the next greater element for each element of nums1 in nums2. If no greater element exists, return -1. 💡 Approach: Use a stack to track the next greater element for all numbers in nums2. Store results in a map for O(1) lookup when iterating nums1. This gives an efficient O(n) solution. 💻 Java Code: class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> mpp = new HashMap<>(); Stack<Integer> st = new Stack<>(); for (int num : nums2) { while (!st.isEmpty() && st.peek() < num) { mpp.put(st.pop(), num); } st.push(num); } while (!st.isEmpty()) mpp.put(st.pop(), -1); int[] ans = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) ans[i] = mpp.get(nums1[i]); return ans; } } ⏱️ Complexity: Time: O(nums1.length + nums2.length) Space: O(nums2.length) ✅ Result: Accepted (Runtime: 0 ms) This problem highlights how monotonic stacks can efficiently solve next-greater-element scenarios without nested loops.
To view or add a comment, sign in
-
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
To view or add a comment, sign in
-
-
🚀 Day 52 of #100DaysOfCode 🚀 Today I solved LeetCode Problem #389 – Find the Difference 🧩 This problem is a great example of using ASCII value manipulation to solve what seems like a string comparison challenge. 💡 Key Learnings: Strengthened understanding of character encoding (ASCII values) and how they can simplify logic. Learned how summing character values can help detect differences efficiently without extra data structures. Reinforced the value of O(n) solutions for string-based problems. 💻 Language: Java ⚡ Runtime: 1 ms — Beats 99.32% 🚀 📉 Memory: 41.9 MB — Beats 65.84% 🧠 Approach: 1️⃣ Convert both strings to character arrays. 2️⃣ Compute the sum of ASCII values of both. 3️⃣ The difference between sums gives the ASCII value of the extra character in t. Simple, elegant, and efficient! ⚙️ Sometimes, a clever use of ASCII arithmetic can replace complex logic — efficiency lies in simplicity. #100DaysOfCode #LeetCode #Java #ProblemSolving #CodingChallenge #Algorithms #DataStructures #SoftwareDevelopment #LearningEveryday #CleanCode
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
-
-
✅Day 42 : Leetcode 154 - Find Minimum in Rotated Sorted Array-2 #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given an array nums that is sorted in ascending order and then rotated between 1 and n times. The array may contain duplicates. Your task is to find and return the minimum element in the rotated sorted array. You must minimize the number of overall operations as much as possible. 💡 My Approach I used a modified binary search technique to handle both rotation and duplicates. Initialize two pointers — low = 0 and high = n - 1. Calculate the middle index mid = low + (high - low) / 2. Update the answer as ans = min(ans, nums[mid]). If nums[low] == nums[mid] && nums[mid] == nums[high], move both low++ and high-- to skip duplicates. If the left half is sorted (nums[low] <= nums[mid]), update the answer and move to the right half (low = mid + 1). Otherwise, move to the left half (high = mid - 1). Continue until low > high. This efficiently finds the minimum even when duplicates exist. ⏱️ Time Complexity Worst Case: O(n) — when many duplicates exist. Average Case: O(log n) — behaves like binary search when duplicates are few. #BinarySearch #LeetCode #RotatedArray #Java #DSA #ProblemSolving #CodingPractice #LeetCodeHard
To view or add a comment, sign in
-
-
💡 LeetCode 3110 – Score of a String 💡 Today, I solved LeetCode Problem #3110: Score of a String, a neat little challenge that emphasizes understanding of ASCII values and absolute differences in Java strings. 🔠✨ 🧩 Problem Overview: You’re given a string s. The score of the string is defined as the sum of the absolute differences between the ASCII values of consecutive characters. Return the total score. 👉 Example: Input → "hello" Output → 13 Explanation → |'e'-'h'| + |'l'-'e'| + |'l'-'l'| + |'o'-'l'| = 3 + 7 + 0 + 3 = 13 💡 Approach: 1️⃣ Initialize a variable sum to store the total score. 2️⃣ Traverse the string from index 1 to end. 3️⃣ For each pair of consecutive characters, find their ASCII difference using Math.abs(). 4️⃣ Add the difference to sum and return it. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the string. ✅ Space Complexity: O(1) — Constant extra space. ✨ Key Takeaways: Strengthened understanding of character encoding and ASCII values. Reinforced clean looping logic and mathematical precision in Java. A great example of how simplicity can elegantly solve a real problem. 🌱 Reflection: Even the smallest coding challenges help sharpen attention to detail — from understanding data types to leveraging built-in functions effectively. Consistency is what transforms learning into mastery. 🚀 #LeetCode #3110 #Java #StringManipulation #ASCII #ProblemSolving #DSA #CodingJourney #CleanCode #AlgorithmicThinking #ConsistencyIsKey
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