🚀 LeetCode Daily Challenge Complete!
Just solved "Find X-Sum of All K-Long Subarrays II" - Part II requires sophisticated two-set optimization!
💡 Solution Evolution:
Naive Approach (TLE):
❌ Rebuild frequency map + heap for each window
❌ O(n × k × log k) - too slow for large inputs
Optimized Two-Set Solution:
✅ Maintain two ordered sets: top (x elements) and bottom (rest)
✅ Track running sum of top set
✅ On element added: Update frequency, rebalance sets
✅ On element removed: Update frequency, rebalance from bottom
✅ O(n log n) - OPTIMAL! ✨
The key insight: Don't rebuild from scratch! Maintain top-x elements in an ordered set ordered by (frequency, value). When frequencies change, efficiently move elements between top and bottom sets. Running sum updates incrementally instead of recalculating!
Critical operations:
- Add: Insert to top, demote smallest if size > x
- Remove: Delete from appropriate set, promote from bottom if needed
- Both operations: O(log n) with set rebalancing
Time: O(n×k×log k) → O(n log n) | Space: O(n)
#LeetCode#HardProblems#CPlusPlus#Algorithms#SoftwareEngineering#ProblemSolving#TwoSetPattern#Optimization
And everyone in our today's problem we have to find axxium of all K long surveys which is problem #2. The description is same as yesterday's problem. But it's a bit hard because if you have a look at our constraints. The plant could go to till at 10 to the power of 5 and numbs and go to the word headline. So if we use our yesterday's solution. Well like for each number we are pushing the number in frequency array. Ohh unordered map and we are maintaining a priority queue and each time we are looking at the priority queue and each time we are like running a low tail X. And adding the sums. Then pushing the sum in the response slope. So it's like it will give you TLA. So what we have to find, we have to find a proposed solution and optimized solution. OK, now if I explain a bit, I. Our solution I've found out is. So the problem statement says. All you have to do is you have to maintain a Klance saveray and find maximum 2 numbers, match find maximum X numbers and return the sum. For example here if this. 123456 Here the frequency of one is 2. Frequency of two is 2. Frequency of three is 1, frequency of four is on. So here top 2. As X equal to 2 so top two number. Is this right because the frequency is bigger so. Return will be like 1/2 times, so 1 + 1. Plus two 2 * 2 + 2 that's it. And the answer will be 6 OK for this 16 again after this one. We know how to solve this one, but the problem is how can we maintain this one with optimal solution? So if you wanna look at the optimal solution, what we're gonna do? Aller Frequencycle Frequency OK? Frequency here and there will be two sat, one will be top. One on the bottom, OK. And on the top, we'll be maintaining. X Land software OK? X length of number, maximum X lengths and then if any number is more than X we will push it on the bottom. OK now for example. This is 1, so frequency of one will be 1, then frequency of. One will be two, So what I'm going to do, I'm going to push the frequency first, so 2/1. Then again. We can see our tool V2 right? So 2 or V2? Then when it will come three, it'll push here. Frequency of three will be one at the beginning. OK, now. The meantime we're going to push them in our top array. OK, so top will be. 2/1. And we're going to maintain a priority queue type thing, so we're going to like sort the sort at top and bottom set in descending order. So the first one will be stood to. Second one will be 2/1. And third one only one three. So at the same time we're going to maintain the top area. We're going to say is the top array. The size of top array is greater than X. If it is greater than X, then take the last number out. Take the last number out. So we're going to remove this one and push it in the. Back, OK. And at the same time what we're going to say. We're gonna like, uh, we're gonna. We're going to run a sum which will be current sum. But here. Regionales Amt, so Till, der will der. Sound like till there or some will be. Still there are some will be. Orglas turistix. 99 OK now. 9 red and when if I move any item to the bottom I'll remove the number as well. So number will be 182. Which will be 9 - 3 six. So kind song will be 6 OK. So till here is OK again it will come on 4. And four. But I'll be pushing, I'll be pushing here. Frequency will be one and four, OK. Then it will. Come here then it will be pushing here 124 OK then the sum will be 6 + 1 into 4 which will be 410 OK now. I'll be checking is my topic today is like the size of Topper is greater than X Yes it is. So what I'm going to do, I'm going to take the last number out this one route and push it here. So as it is greater than 1/3, so one will go later 14 will come here. The sun is 4913 will go there OK. Then when I push, when I remove it from the top, I have to like reduce it from our current sum. So current sum will be 10 -, 1 into 4 which will be. 6 again OK now till here I got my size OK 6 So if I see we got our size of K, what I'm going to do I'm going to push my current sum. Hello. The response will be sticked. Now again, I'm going to increase the value of I. So if it is greater than 6, which is yes, the size is greater than six, I'm going to reduce one number from here. So this one I'll find, I'll find the number. Frequency of 1. So what was the frequency of one? It was 2, right? So what I'm going to do? I'm going to take this one out. On top. All of them. I'm going to take this one out. 1-2 I'm going to push it here. If I find it. I cannot push it here. Buat aldo aldo stay it out. And I'm going to do -1 into two, whichever whatever I like taken out so. Big Finastra which will be 4. And by this time, by this time. Like. OK, well. What I'll do here, whenever I'll be coming here, right? Whenever I'll be coming here, the frequency 2 will be 3, so that one I have to update first, OK, Frequency of toiletry, Right now I have to remove the first one. So what I'll do? I'll remove the whole thing. And I'll be removing the current sum will be umm. Kind of. Some will be 6 three into 2666 plus 28. The current song will be 8. OK 8 now. I'll be removing this one, so I'll be removing this one S 8 - 2 which will be 6/6. But. If it is fixed and if. If it is 6 what I'm going to do? I'll say if the count was if the count was more than one, which was true for this one, I'll push it in the bottom. -1 OK I'll reduce the count 1 as I'm losing here so I'll push it in the bottom. The frequency of one will be 1 which is true light frequency of one will be 1 because I'm counting now till there right then. I'll be saying if my top size is less than X. And I'll be taking the first fellow from bottom. I hope you got it. So my answer will be 6 plus first value of bottom. Which one will be 1 into 4? 1 into 4. So 6 + 4 which is equal to 10. OK, so I'll be pushing 10 here and we got it then. Then I'll delete this one. OK now. In that case, if you want, we can push it here, right? In that case. I'm gonna push it here one and four. That's it, OK. Now I'm going to three and I found out frequency of three is 2, so I'll push it here. OK. Then. Then what I will do? I'll be pushing it as this one has three. I'll be pushing it 2:00 and 3:00 so it will come here. OK, so true 3 S 2 is greater than one. Then the sum will be 10 + 2 into 3 equal to 6. Which channel 16? 16. Exchange then. I'll be removing this one. Because I need to maintain like the size so it will come here again. As it is the maximum number and then again the value will be. 6 + 6 which will be 12. So. 12 OK. 12. Then I I'll like I I'm there and I'll remove this one. So I'll count out the frequency. The frequency of one is 1. And it's not in the top area. So I can just. Imprivata return this summer shelf. That's it. The answer is 6/10/12. OK now if I, if I like, put my theory on code. I know the solution and the theory is a bit complicated. As we have to maintain so many arrays, frequency arrays, unordered map set and sums and we have to like keep removing top, bottom at. So it's this kind of overwhelming for the time being, but as soon like as long as you're gonna do the solution, it will be like a bit. Easier for you guys. So what do I have to find? I'll declare the fighter. Long, long. Response and I'll be returning response. OK, let's try to always first. What I'll take, I'll take one another map. Unordered map. Dan sekarang non redmap pak alb. If counting the frequency OK now for this one, you can set this one as a long long but I'll keep it in the integer later if we got any error I'll keep him long long OK. I got my frequency then I need to set. And have been maintaining up here. I enter here int. That will be top. Welcome. And then?
🚀 LeetCode Problem Spotlight: Rotate Image (90° Clockwise)
I recently revisited one of my favorite matrix manipulation problems — “Rotate Image” (LeetCode #48) — and it reminded me how elegant simple logic can be when used effectively.
🧩 The Challenge
Given an n x n matrix representing an image, the goal is to rotate it 90° clockwise — in place, without using any extra space.
💡 The Insight
The trick lies in realizing that a rotation doesn’t require rebuilding the matrix — just transforming it cleverly.
Here’s how:
1️⃣ Transpose the matrix — swap rows and columns.
2️⃣ Reverse each row — and just like that, the image is rotated!
Two small transformations, one clean solution.
⚙️ Complexity
⏱ Time: O(n²)
💾 Space: O(1)
🧠 Takeaway
This problem is a great reminder that complex outcomes often come from simple, well-structured steps.
It’s less about memorizing algorithms and more about understanding the data flow behind them.
How would you approach this problem — any creative twists or optimizations you’ve tried?
Let’s discuss 👇
📌 Day 39/150 – Rotate List (LeetCode #61)
Today’s problem was a brilliant exploration of how subtle linked list operations can completely change the shape of a data structure! 🔁✨
The task?
Given a linked list, rotate it to the right by k positions.
Instead of shifting values, we must carefully adjust the links — no cheating with arrays! 😄
This problem reinforces how pointer manipulation and structural thinking work hand-in-hand in linked list questions. 🧠
🔹 Brute Force Idea
A naive thought would be:
👉 Rotate one step at a time
👉 Move the last node to the front
Repeat this k times.
✅ Easy to visualize
❌ Too slow (k rotations × n operations = inefficient!)
❌ Not scalable for large k
🔹 Optimal Approach – Smart Pointer Manipulation
The elegant approach lies in understanding patterns:
👉 First, compute the length of the list.
👉 Connect the tail to the head — forming a temporary circle! 🔄
👉 Reduce k using modulo (k = k % length)
👉 Traverse to the correct breaking point.
👉 Break the circle to form the rotated list.
You handle:
🔸 Circular linked list logic
🔸 Tail–head reattachment
🔸 Precise pointer breaking
Very clean, very efficient! ✨
🧠 Example Visualization
Input:
1 → 2 → 3 → 4 → 5, k = 2
After rotation:
4 → 5 → 1 → 2 → 3
Only the links change — the magic of pointers! 🔧
⏱️ Time & Space Complexity
ComplexityValueTimeO(n) — just one traversalSpaceO(1) — done in-place
💡 Key Learning:
This problem helps build confidence in:
✅ Recognizing patterns
✅ Using circular logic
✅ Efficient pointer manipulation
✅ Avoiding unnecessary extra space
It’s one of those linked list questions that feels intimidating at first, but becomes satisfying once you see the strategy.
Solving this opens the door to related problems like:
📍 Rotate Array
📍 Reverse Nodes in K-Group
📍 Swap Nodes in Pairs
Linked lists may bend… but they don't break your confidence anymore. 💪😄
#150DaysOfCode#LeetCode#RotateList#LinkedLists#Pointers#DSA#CodingChallenge#SoftwareEngineering#LearningJourney#ProblemSolving 🚀🔥
🚀 Day 68 of #100DaysOfLeetcodeHard — LeetCode 2382: Maximum Segment Sum After Removals (Hard)
My Submission:https://lnkd.in/g-X4k2Hd
Today’s challenge was a Disjoint Set Union (Union-Find) problem with a clever reverse processing approach.
🧩 Problem Summary:
We start with an array and remove elements one by one, needing to track the maximum segment sum of contiguous non-removed elements after each removal.
Instead of simulating removals forward (which is difficult to track), we reverse the process —
✅ Start from an empty array and add elements back in reverse order.
✅ Use Union-Find (Disjoint Set) to merge adjacent active segments and maintain their sums dynamically.
💡 Approach:
Each index starts as its own segment with rank[i] = nums[i] (used to store segment sums).
When a new index is added, we union it with its active neighbors (if any).
Track the maximum segment sum after each merge.
🧠 Key Concepts Used:
Union-Find with path compression & rank to efficiently merge contiguous segments.
Reverse iteration to avoid handling splits directly.
📈 Complexity:
Time: O(n α(n)) ≈ O(n) (inverse Ackermann function for DSU)
Space: O(n)
A beautiful mix of data structures + reverse simulation + problem insight — one of those problems that truly sharpen algorithmic thinking. ⚡
#LeetCode#UnionFind#DSU#ProblemSolving#AlgorithmDesign#DataStructures#CodingChallenge#100DaysOfCode#LearningEveryday
🌟Day 64
LeetCode: Combination Sum (39)
Approach: Backtracking 🔁
✨ Explored all possible combinations where numbers can be reused to reach the target. Used recursion to build combinations, backtrack when the sum exceeds the target, and store valid results when matched.
📈 Learned how backtracking helps in exploring multiple decision paths efficiently — building logic for recursion-heavy problems.
#LeetCode#100DaysOfCode#Backtracking#Recursion#CodingJourney#ProblemSolving
🚀 Day 48 (Leetcode)
Problem: Split Linked List in Parts
🧠 Approach (C++):
1. First, calculate the total length l of the linked list.
2. Determine how many nodes should go in each part → eachBucketNodes = l / k.
3. Calculate how many parts should get one extra node → remainderNodes = l % k.
4. Iterate through the list and break it into k parts:
Each part gets eachBucketNodes nodes.
If any remainder exists, the first remainderNodes parts get 1 extra node.
5. Use a prev pointer to disconnect each part cleanly (prev->next = NULL).
✨ Learning: This problem beautifully reinforces how to handle variable-sized partitions and precise pointer cuts in linked lists
🚀 LeetCode Daily Challenge Complete!
Just solved "Final Value of Variable After Performing Operations" - a simple yet elegant problem that teaches the value of finding shortcuts in pattern matching!
💡 Solution Approach:
✅ Iterate through all operation strings
✅ Check middle character (index 1)
✅ If '-': decrement, if '+': increment
✅ Return final value
The key insight: Instead of comparing full strings ("--X", "X--", "++X", "X++"), we can observe that ALL operations have the operator in the middle position! By checking just op[1], we instantly know whether to increment or decrement.
Pattern recognition:
"--X" and "X--" both have '-' at index 1 → decrement
"++X" and "X++" both have '+' at index 1 → increment
This single-character check is more efficient than string comparisons!
Time Complexity: O(n) | Space Complexity: O(1)
#LeetCode#StringParsing#CPlusPlus#Algorithms#SoftwareEngineering#ProblemSolving#CleanCode#PatternRecognition
🌟 Day 105 of My LeetCode Journey — Problem 138: Copy List with Random Pointer
💡 Problem Insight:
Today’s problem took linked lists to a new level — each node had not just a next pointer but also a random pointer that could point to any node (or null). The challenge was to create a deep copy of such a list, preserving both connections perfectly.
🧠 Concept Highlight:
The efficient approach involves three smart steps:
Clone each node and insert it right next to the original node.
Set up random pointers for the cloned nodes.
Detach the two lists to restore the original and extract the copy.
This clever interleaving technique avoids extra space (no hash map needed) and runs in O(n) time — an elegant display of pointer manipulation.
💪 Key Takeaway:
Duplication isn’t about copying blindly — it’s about understanding the relationships and structure beneath the surface.
✨ Daily Reflection:
This problem reinforced that clean logic and visualization make even the most pointer-heavy tasks simple and satisfying.
#Day105#LeetCode#100DaysOfCode#LinkedList#ProblemSolving#RandomPointer#DeepCopy#DSA#CodingJourney#LearnByDoing#SoftwareEngineering
🔍 Day 66 of #100DaysOfCode 🔍
🔹 Problem: Binary Search – LeetCode
✨ Approach:
Implemented an iterative binary search to efficiently locate the target element within a sorted array.
By halving the search range each time — adjusting low and high around the mid-point — the algorithm achieves blazing-fast lookups! ⚡
📊 Complexity Analysis:
Time Complexity: O(log n) — array size halves with each iteration
Space Complexity: O(1) — constant extra space
✅ Runtime: 0 ms (Beats 100.00%)
✅ Memory: 46.02 MB
🔑 Key Insight:
Binary Search is proof that efficiency isn’t about doing more — it’s about eliminating what’s unnecessary. 🚀
#LeetCode#100DaysOfCode#ProblemSolving#DSA#AlgorithmDesign#BinarySearch#LogicBuilding#Efficiency#ProgrammingChallenge#CodeJourney#CodingDaily
📽 Watch the full explanation here: https://youtu.be/l6ZEvRGGguA