🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gdjyFXCw First, we note that swaps aren't random; they are only allowed between specific index pairs. If index `a` can swap with `b`, and `b` can swap with `c`, then `a`, `b`, and `c` become connected. We can rearrange values freely among them. This means we need to identify groups of indices where swapping is allowed within the group. To find these groups efficiently, we use Disjoint Set Union (DSU). Each index starts in its own set. For every allowed swap pair `[x, y]`, we combine their sets. After processing all the swaps, indices that share the same parent belong to the same connected component or group. Next, we organize all indices by their DSU parent. Each group shows a set of positions where we can rearrange values without restrictions. For each group, we aim to match values from `source` to `target` as closely as possible: * First, we count how often each value appears in `source` for that group. * Then, we go through the same indices in `target`. For each value: * If the value exists in our frequency map (meaning we have it in `source`), we use it and decrease its count. * If it doesn't exist, it means we can't match this value in the group, contributing to the Hamming distance. By doing this for all groups, we maximize matches within each connected component, which minimizes the overall Hamming distance. 👉 My Solution: https://lnkd.in/gfx3iMut If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
LeetCode Daily Challenge: Disjoint Set Union for Grouped Swaps
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gqTik3da 💡 My thought process: First, save all indices of each number in a map. The key is the number, and the value is a sorted list of its positions in the array. Then, for every index i, it computes the reverse of nums[i]. While reversing, it skips leading zeros. This means that a number like 120 becomes 21 instead of 021. After getting the reversed number, check the map for all indices where this reversed value exists. Using upper_bound, find the first index that is strictly greater than i. If such an index exists, calculate the distance between the two indices and update the minimum distance. Finally, if no such pair is found, it returns -1. Otherwise, it returns the minimum distance found. 👉 My Solution: https://lnkd.in/gpNu3WGh If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g9SGp2Qa 💡 My thought process: First, create a mapping from each value to a sorted list of its indices using a map<int, vector<int>>. This allows for easy lookup of all positions where a value occurs. For each query index idx, it retrieves the corresponding value num. If that value appears only once, the result is -1 because no valid pair exists. In case of multiple occurrences, we use binary search on the index list of num: * upper_bound finds the next occurrence that is strictly greater than idx. * lower_bound locates the current position and checks the previous occurrence. It calculates distances in both directions: * Forward distance: either direct (next - idx) or circular wrap (n - (idx - first)). * Backward distance: either direct (idx - prev) or circular wrap (n - (last - idx)). The minimum of these distances is stored as the answer. 👉 My Solution: https://lnkd.in/gjmKVa3y If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g8Xgd5wx The function goes through each word in the `queries` array. For every query word, it compares it with each word in the `dictionary`. Since all words are assumed to have the same length, it performs a character-by-character comparison. For each pair of words, a counter called `unequal` tracks how many positions have different characters. The code loops through each index of the word and increases this counter whenever the characters at the same position do not match. If the number of differing characters is 2 or less at any point, it means the query word can change into that dictionary word with at most two edits. In this case, the query word is added to the result list, and the inner loop stops early, using `break` to avoid unnecessary comparisons with other dictionary words. Finally, after checking all query words, the function returns the list of valid words that meet the condition. 👉 My Solution: https://lnkd.in/gMnYvSvx If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gZ52pSZR 💡 My thought process: The solution operates in two separate passes: 1. Left-to-Right Pass: For each element at index "i", calculate the distance to all previous occurrences of that value. If a value has appeared "k" times before, the sum of distances is found using this formula: (count * current_index) - (sum of previous_indices). By storing the count and the running sum of indices in a hash map, we can compute this in constant time. 2. Right-to-Left Pass: The same logic is applied in reverse to calculate the distance from the current index to all future occurrences. In this case, the formula changes to: (sum of future_indices) - (count * current_index). By adding the results from both directions, the code captures the total absolute difference for every identical pair without the performance cost of a nested loop. 👉 My Solution: https://lnkd.in/gfEc7Kis If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering
To view or add a comment, sign in
-
-
🚀 Solved LeetCode Problem #47 – Permutations II Today I tackled a classic backtracking problem that adds an interesting twist—handling duplicate elements while generating permutations. 🔍 Problem Insight: Given an array that may contain duplicates, the goal is to generate all unique permutations without repetition. 💡 Approach Used: I used a Backtracking + Sorting strategy: First, sort the array to bring duplicates together Use a visited[] array to track used elements Apply a smart condition to skip duplicate choices during recursion This ensures that we only generate distinct permutations efficiently. 🧠 Key Learning: Handling duplicates in recursive problems is crucial Sorting helps simplify duplicate detection Backtracking becomes powerful when combined with pruning conditions 📈 Complexity: Time: O(n!) Space: O(n) ✨ This problem strengthened my understanding of: Backtracking techniques Recursion control and pruning Writing optimized solutions for combinatorial problems Consistency in solving such problems is helping me build stronger problem-solving skills every day! 💪 #LeetCode #DSA #Backtracking #Algorithms #Coding #ProblemSolving #Java #TechJourney
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gdWsKciF This solution finds the maximum distance between two houses of different colors based on a key observation: the maximum distance will always involve either the first house or the last house. Instead of checking all possible pairs, which would take O(n²), the code improves the method by making a single pass through the array. It starts with an answer of 0 and goes through each index `i`. For each house, it does two checks. First, it compares the current color with the color of the first house (index 0). If they are different, the distance between them is simply `i`, and we update the maximum distance. This identifies the farthest house from the start that has a different color. Next, it compares the current color with the color of the last house (index n-1). If they are different, the distance is `(n - 1 - i)`, and we update the maximum if necessary. This identifies the farthest house from the end that has a different color. By doing this, the algorithm effectively captures the maximum possible distance without checking every pair. Since it requires only one loop through the array, the time complexity is O(n) and the space complexity is O(1). 👉 My Solution: https://lnkd.in/gg_5J_DF If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/eGmHt3nW The grid consists of six street types, and each allows movement in exactly two directions. These types are outlined in a map at the start: - Type 1: left/right - Type 2: up/down - Type 3: down/left - Type 4: down/right - Type 5: left/up - Type 6: right/up The depth-first search (DFS) begins at the point (0,0) with a marker `{-2,-2}`, indicating "no incoming direction yet." Before moving on from any cell, two checks are necessary: When reaching a cell using the direction `{dir1, dir2}`, the current street must include `{-dir1, -dir2}` in its connection list. This represents the exact opposite direction and confirms the street physically connects back to where you came from. If neither of the two connections matches, the path is deemed invalid, and the process returns false right away. As streets make up a fixed graph with possible cycles, the `visited` marker identifies cells that have already been seen before checking neighboring cells. Any neighbor that is already marked is skipped. Without this, the DFS would loop through a cycle endlessly. The check for the incoming direction alone cannot prevent this, as it only reveals the immediate previous direction, not the entire path taken. Once both checks are satisfied, the cell is marked as visited, and DFS explores unvisited neighbors. Each street has precisely two connections, leading to a maximum of two neighbors to consider. In practice, one neighbor is usually blocked by the `visited` marker (the cell you just came from), so most steps tend to be linear rather than branching. 👉 My Solution: https://lnkd.in/e8-6pePg If you found this helpful, feel free to ⭐ the repo or connect! 🙂 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
Day 2: Leetcode – 704. Binary Search Today’s problem looked straightforward, but it exposed how small mistakes in control flow can completely break the logic. The Key Insight: Binary search isn’t just about comparing values — it’s about maintaining the correct search space and letting the loop run until it’s fully exhausted. Returning too early can silently ruin the entire algorithm. My Mistake: I placed return -1 inside the loop, which caused the function to exit after just one iteration if the target wasn’t found immediately. The code compiled fine but the logic was wrong — a good reminder that passing compilation doesn’t mean correctness. My Approach: Initialize low = 0 and high = n-1 Calculate mid each iteration Compare nums[mid] with target Adjust search space accordingly Only return -1 after the loop ends Takeaway: Binary search is simple in theory but demands discipline in implementation. One misplaced return or bracket can turn a correct idea into a faulty solution. Day 2 Completed #LeetCode #DSA #BinarySearch #Learning #CodingJourney
To view or add a comment, sign in
-
-
🚀 Solved LeetCode Problem #22 – Generate Parentheses Today I worked on an interesting recursion + backtracking problem that really strengthens understanding of constraint-based generation. 🔍 Problem Insight: Given n pairs of parentheses, generate all combinations of well-formed parentheses. 💡 Key Idea: Instead of generating all combinations and filtering invalid ones, we build only valid strings by: Adding '(' only when we still have some left Adding ')' only when it won’t break validity (i.e., open > close) 🧠 This ensures we never create invalid sequences, making the solution efficient. ⚙️ Approach Used: Backtracking (DFS) with two counters: open → number of '(' used close → number of ')' used 📈 Complexity: Time complexity follows Catalan Numbers → grows approximately as O(4^n / √n) ✨ Key Learning: This problem highlights how smart constraints in recursion can avoid unnecessary computation and lead to optimal solutions. 📌 Problems like this are great for mastering: Recursion Backtracking Combinatorial generation #LeetCode #Coding #DSA #Recursion #Backtracking #Java #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 34/100 – DSA Practice (LeetCode) Today I solved “367. Valid Perfect Square” problem. 🔹 Problem Summary: Given a positive integer num, check whether it is a perfect square without using built-in functions like sqrt(). 🔹 What I Learned Today: A perfect square means: → x * x = num where x is an integer Avoiding built-in functions improves problem-solving skills Learned how to think mathematically + logically Practiced loop-based checking approach Understood importance of constraints (large inputs) 🔹 My Approach: Start from i = 1 Calculate i * i If it equals num → return true If it exceeds num → stop and return false ✔ Simple and beginner-friendly approach ✔ No built-in functions used 🔹 Example: Input: 16 → Output: true ✅ Input: 14 → Output: false ❌ 💡 Key Takeaway: Instead of relying on built-in methods, building logic from scratch strengthens problem-solving skills. ⚠️ Missed yesterday’s update due to network issues, but back on track today! #Day34 #100DaysOfCode #DSA #Java #LeetCode #CodingJourney
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