🚀 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
LeetCode Daily Challenge: Reverse Pairs in Array
More Relevant Posts
-
🚀 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/gxcUfyyz The first logic that came to my mind after seeing the question was — this is a cycle detection problem. Since the path isn't fixed, it's an undirected cycle detection problem. Just applied that and voila — solved! The constraints and multiple possible paths gave a clear hint towards DFS. The grid is just an undirected graph — each cell is a node, and two adjacent cells are connected only if they share the same character. So the problem reduces to: does any connected component of same-character cells contain a cycle? Run DFS from every unvisited cell, tracking the parent to avoid treating the edge we came from as a back edge. If we hit an already-visited cell that isn't our direct parent — cycle found. ⏱️ Time: O(m × n) | Space: O(m × n) 👉 My Solution: https://lnkd.in/gATmwcnU 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
-
-
🚀 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
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
-
-
🚀 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
-
-
🚀 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
-
-
200 problems solved on LeetCode. The number is visible. The process isn't. Behind those 201 accepted solutions: • 339 submissions — most of them wrong • Hours lost debugging a single edge case • Concepts revisited from scratch, more than once • 157 active days. Not perfect. Just present. And somewhere along the way, something quietly shifted. • Medium problems are now the default, not the scary ones • A 60-day streak taught me what discipline actually feels like • Confidence stopped coming from guessing — it started coming from understanding 86 Easy. 104 Medium. 11 Hard. Each category has its own lesson. None of them were free. This isn't a flex. It's a record of showing up — in C++, one problem at a time, on the days it felt productive and especially on the days it didn't. Progress didn't come from perfect days. It came from staying consistent on imperfect ones. Still learning. Still building. 🎯 Next: depth over count — stronger fundamentals, sharper problem-solving, better contest performance. Consistency compounds. Always. #LeetCode #DSA #CPP #CompetitiveProgramming #Consistency #ProblemSolving #Growth #100DaysOfCode
To view or add a comment, sign in
-
-
Day 45 of solving LeetCode problems. Solved: Defuse the Bomb This problem looks simple, but it tests a key concept — handling circular arrays with a sliding window. Instead of recalculating sums repeatedly (O(n*k)), I used a rolling window to bring it down to O(n). The tricky part was managing indices correctly when moving forward vs backward (k > 0 vs k < 0). Key takeaway: Efficient thinking is about avoiding redundant work, not just getting the correct answer. Consistency is good, but improving how you think matters more. #leetcode #dsa #problemSolving #coding #100DaysOfCode
To view or add a comment, sign in
-
-
Ever look at a LeetCode problem and think, "Oh, this is just simple math," only to see a constraint of $10^{15}$ staring back at you? That was my experience with the "Count Good Numbers" problem today. The core logic was actually pretty straightforward: even indices get even digits (5 options), and odd indices get prime digits (4 options). But trying to calculate 5^even * 4^odd for massive numbers? Immediate Time Limit Exceeded (TLE). I had to scrap the standard approach and write a custom pow() function using Binary Exponentiation. It’s wild how applying modulo 10^9 + 7 at every single multiplication step within the recursive call is the exact difference between a failing solution and a clean O(log n) pass without integer overflow. Definitely a great reminder that knowing the brute-force math is only half the battle—optimizing it is where the real engineering happens. Back to the grind! #LeetCode #DSA #CPP #CompetitiveProgramming #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7 of LeetCode Problem Solving Solved today’s problem — LeetCode #414: Third Maximum Number 💻🔥 ✅ Approach: Tracking Top 3 Maximums ⚡ Time Complexity: O(n) 📊 Space Complexity: O(1) The challenge was to find the third distinct maximum number in an array. If it doesn’t exist, return the maximum number. 👉 Instead of sorting (which takes extra time), I tracked the top 3 distinct maximum values in a single pass. 💡 Key Idea: Maintain three variables (max, smax, tmax) to store the first, second, and third maximum values while traversing the array. 👉 Core Logic: Skip duplicates Update max, second max, third max accordingly If third max doesn’t exist → return max 💡 Key Learning: Optimizing from sorting to a single-pass solution can significantly improve efficiency. Grateful to my mentor Pulkit Aggarwal — your guidance is helping me think more optimally 🙌 Consistency is the key — improving step by step 🚀 #Day7 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #100DaysOfCode
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