Hello Everyone, Day 14 / #100DaysOfCode LeetCode 3454 — Separate Squares II (Hard) This problem was on a completely different level. Unlike Separate Squares I, overlapping areas here must be counted only once, which immediately rules out simple area accumulation or binary search tricks. Approach: Scan Line + Segment Tree (Adapted from the editorial and inspired by LeetCode 850 — Rectangle Area II) Core idea: - Sweep a horizontal scan line from bottom to top - Convert each square into two events: - Bottom edge → +1 coverage - Top edge → -1 coverage - Maintain active horizontal coverage using a segment tree with lazy propagation - At any vertical slice: - covered area = width × height - Width is the total x-length where coverage > 0 What the segment tree tracks: - Coverage count for each x-interval - Total covered length when count > 0 Using this, we compute the total covered area. Then, during the same scan, we locate the smallest y such that: area_below(y) = totalArea / 2 Since coverage stays constant between two scan events, the exact y can be computed analytically inside that interval. Complexity: - Time: O(n log n) - Space: O(n) Honest takeaway: I couldn’t crack this one independently and relied heavily on the editorial. Problems like this genuinely feel Extra Hard — combining geometry, sweep-line algorithms, discretization, and segment trees in one go. LeetCode has definitely raised the bar. #LeetCode #HardProblems #DSA #Java
LeetCode 3454: Separate Squares II Solution
More Relevant Posts
-
🚀 Day 23 – LeetCode 1208 | Get Equal Substrings Within Budget Today’s problem focused on optimizing substring transformations under a cost constraint. 🧠 Problem Given two strings "s" and "t", each character change has a cost defined by the ASCII difference. Find the maximum length substring that can be converted within a given budget. 🔍 Key Insight Instead of brute force (O(n²)), convert the problem into: → “Longest subarray with sum ≤ k” This immediately maps to the Sliding Window (Two Pointer) technique. ⚙️ Approach • Calculate cost = |s[i] − t[i]| • Expand window → add cost • If budget exceeded → shrink window • Track max length ⏱ Complexity Time: O(n) Space: O(1) 💻 Code (Java) class Solution { public int equalSubstring(String s, String t, int maxCost) { int left = 0, currentCost = 0, maxLen = 0; for (int right = 0; right < s.length(); right++) { currentCost += Math.abs(s.charAt(right) - t.charAt(right)); while (currentCost > maxCost) { currentCost -= Math.abs(s.charAt(left) - t.charAt(left)); left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen; } } 📌 Takeaway Whenever you see: • longest substring • contiguous • sum constraint Think → Sliding Window Pattern recognition > memorizing solutions. #LeetCode #DSA #SlidingWindow #Java #ProblemSolving #CodingInterview #SoftwareEngineering #100DaysOfCode #Developers #TechCareer
To view or add a comment, sign in
-
LeetCode POTD #3013 - Divide an Array Into Subarrays With Minimum Cost II (02 February 2026) This one looks messy at first glance, but the trick is how you frame it. The first subarray is forced to start at index 0. So the real decision is where the last subarray starts. Fix the starting index of the last subarray at i. Now the constraint i(k-1) - i1 <= dist forces the remaining k-2 subarrays to start inside the window: [i - dist, i - 1] At that point, the problem becomes clean: From a sliding window of length dist, continuously maintain the smallest k-2 values. To do this efficiently: -> Use two ordered sets -> One keeps the k-2 smallest elements -> The other holds the rest -> Maintain the sum while the window slides Total cost for each i: nums[0] + nums[i] + sum_of_k-2_smallest Minimum across all valid i is the answer. Key takeaway: Hard problems usually aren’t about complex code -> they’re about choosing the right perspective. Time Complexity -> O(n log n) Space Complexity -> O(n) #LeetCode #POTD #HardProblems #DataStructures #SlidingWindow #Java #ProblemSolving
To view or add a comment, sign in
-
-
Day 33 / #100DaysOfCode LeetCode 3013 — Divide an Array Into Subarrays With Minimum Cost II (Hard) Problem (short): Given an array nums, divide it into k subarrays such that: - The first subarray must start at index 0 - The distance between the start of the 2nd and kth subarray is at most dist - The total cost (sum of starting elements of all subarrays) is minimized This is the Hard follow-up of Part I, and the constraints make brute force impossible. Key Challenge: Once k becomes variable, we are no longer choosing just 2 elements. We must dynamically maintain the minimum sum of (k-2) valid starting elements inside a moving window. This is where simple sorting or greedy breaks. Core Idea / Observation: - nums[0] is always included - For each possible ending index, we need: • the smallest (k-2) elements from a sliding window • fast insertion and deletion • fast access to the smallest elements This naturally leads to a two-multiset (two TreeMap) strategy. Approach: 1. Fix nums[0] as the first subarray 2. Use two TreeMaps: • st1: stores the smallest (k-2) elements (contributes to sum) • st2: stores the remaining elements 3. Maintain balance using: • automatic shifting between maps • invariant: st1 always contains exactly (k-2) smallest elements 4. Slide the window while respecting the dist constraint 5. At each step: • compute current cost = nums[0] + sum(st1) + current element • update minimum I did take help from the editorial here — to understand how to maintain the invariant correctly. This problem is more about data-structure discipline than raw logic. Complexity: - Time: O(n log n) - Space: O(k) (due to TreeMaps) #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
Hello Everyone, Day 19 / #100DaysOfCode LeetCode 1292 — Maximum Side Length of a Square with Sum ≤ Threshold (Medium) Problem (brief): Given an m × n matrix of non-negative integers and a threshold, find the maximum side length of a square submatrix whose sum is ≤ threshold. Why this was tricky (for me): Matrix problems still slow me down. Not because they’re impossible—but because without the right preprocessing, everything turns into brute force chaos. Once again, the editorial clarified the first key idea. Core Idea: Use a 2D prefix sum matrix to compute the sum of any square in O(1) time. Let P[i][j] store the sum of the submatrix (1,1) → (i,j). Then any square sum can be computed as: sum = P[x2][y2] - P[x1-1][y2] - P[x2][y1-1] + P[x1-1][y1-1] Optimized Enumeration Strategy: Naively, we’d use three nested loops: - Top-left corner (i, j) - Side length c But two important optimizations help: 1. Monotonicity: All values are non-negative. If a square of size c exceeds the threshold, any larger square at the same position will also fail → break early. 2. Global Best Tracking: If we’ve already found a valid square of size ans, there’s no point checking sizes ≤ ans again. Start directly from ans + 1. These two observations significantly reduce unnecessary checks. Complexity: - Time: ~ O(m⋅n⋅min(m,n))O(m · n · min(m,n))O(m⋅n⋅min(m,n)) (with strong pruning) - Space: O(m⋅n)O(m · n)O(m⋅n) for prefix sums Takeaway: This wasn’t about inventing a clever trick—it was about recognizing when prefix sums + pruning turn brute force into something practical. Matrix problems are still uncomfortable for me, but at least now I know why the solution works—not just that it works. #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
🚀 Day 67 of #100DaysOfCode Today’s problem focused on 2D Prefix Sum optimization — Range Sum Query 2D – Immutable (NumMatrix) 📊 At first glance, this problem looks like repeated matrix traversal, but the real win comes from preprocessing smartly. 📌 Problem Summary You’re given a 2D matrix and multiple queries asking for the sum of elements inside a sub-rectangle. Brute force would be too slow for repeated queries. 🧠 My Approach: Prefix Sum (Row-wise) Precompute prefix sums for each row For every query, calculate the sum in O(rows) time using prefix subtraction Avoid recalculating sums for every query This transforms repeated heavy computation into a fast query process ⚡ ⚙️ Time & Space Complexity Preprocessing: O(rows × cols) Each Query: O(rows) Space: O(rows × cols) 🔥 Key Learning Prefix sums are not limited to 1D arrays— they scale beautifully to 2D problems and are extremely powerful for range queries. Another solid step forward in mastering optimization techniques 💪 On to Day 68 🚀 #Day67 #100DaysOfCode #Java #LeetCode #PrefixSum #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
LeetCode 3010: Divide an Array Into Subarrays With Minimum Cost I — a neat “read the definition carefully” problem I enjoyed this one because it looks like a partitioning problem… but the optimal solution is just a simple scan. Key insight: When you split the array into 3 subarrays, the cost = sum of the first element of each subarray. The first subarray must start at index 0, so nums[0] is always included. You’re free to choose where subarray 2 and 3 start (somewhere in nums[1..]). To minimize cost, you simply pick the two smallest values from nums[1..]. So the answer is: nums[0] + smallest(nums[1..]) + secondSmallest(nums[1..]) Leetcode problem link:https://lnkd.in/gUrES9Td #leetcode #java #datastructures #algorithms #problemsolving
To view or add a comment, sign in
-
-
LeetCode POTD #2976 - Minimum Cost to Convert String I (29/01/2026) This problem looks deceptively simple. Two strings, some character conversions, find the minimum cost. But the moment you try to do it greedily per character, things start breaking. The real problem is not string manipulation. It’s a shortest path problem on characters. Each character is a node. Each allowed conversion is a directed edge with a cost. And conversions can be chained. Once you see that, the solution becomes straightforward: build a graph of 26 characters and run Floyd Warshall to compute the minimum cost between every pair. Why Floyd Warshall? Because the graph is tiny, fixed size, and we need all-pairs shortest paths, not just one source. After preprocessing: iterate once over the strings and sum up the cost of converting source[i] to target[i]. If any conversion is unreachable, return -1. What I liked about this problem is how quickly it punishes surface-level thinking. The constraints force you to model the problem correctly, or you’ll keep patching edge cases. Clean graph modeling beats clever hacks every single time. #LeetCode #POTD #Graphs #FloydWarshall #ProblemSolving #Java #Consistency
To view or add a comment, sign in
-
-
Day 42 - LeetCode Journey 🚀 Solved LeetCode 944: Delete Columns to Make Sorted in Java ✅ Today’s challenge was all about looking at data from a different perspective—literally! Instead of the usual row-by-row string processing, I had to shift my focus to vertical column-wise traversal. The Problem: Given an array of strings, imagine them stacked to form a grid. The goal is to identify and "delete" any columns that are not sorted lexicographically. The Approach: Grid Traversal: Used nested loops where the outer loop iterates through columns and the inner loop iterates through rows. Lexicographical Check: For each column, I compared characters at index row and row + 1. Optimization: As soon as a single out-of-order pair is found in a column, the break keyword ensures we stop checking that column and move to the next, keeping the solution efficient. Key Takeaways: Column-Major Order: Reinforced how to swap the standard matrix[i][j] traversal to focus on vertical data. String Manipulation: Continued practicing charAt() for precise character comparisons within a string array. Problem Decomposition: Breaking down a visual grid into simple loop logic is a crucial skill for more complex matrix problems. Whether it's pattern matching or grid manipulation, every problem is a new tool in the kit. Consistency is doing its work! 💪 #LeetCode #DSA #Java #Strings #Algorithms #ProblemSolving #CodingPractice #InterviewPreparation #Consistency #DailyCoding
To view or add a comment, sign in
-
-
Day 38: Efficiency through String Balancing! ⚖️ Problem 1653: Minimum Deletions to Make String Balanced Today’s challenge was to find the minimum deletions needed to ensure no 'b' comes before an 'a' in a string. It’s a classic problem that tests your ability to think about state transitions across a sequence. I implemented a prefix/suffix counting strategy. Instead of brute-forcing every deletion possibility, I pre-calculated the total count of 'a's and then iterated through the string while keeping a running count of 'b's. At each position, the sum of 'b's seen so far (to be deleted if they stay) and 'a's remaining (to be deleted if they appear later) gave me the cost to balance at that specific "split point." By tracking the minimum sum across all possible split points, I achieved a clean O(n) solution with just two passes. It’s a great reminder that sometimes "balancing" a problem is just about counting what’s on either side of the fence! #LeetCode #Java #StringAlgorithms #Optimization #CodingChallenge #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 21 of #100DaysOfCode 🧩 Problem: Find Median of Two Sorted Arrays (LeetCode #4, Hard) 💡 Concept: Given two sorted arrays, the goal is to find the median of the combined dataset after merging both arrays. 🛠 Approach (Merge + Sort): 1️⃣ Create a new array to store elements from both input arrays. 2️⃣ Copy all elements from nums1 and nums2 into the new array. 3️⃣ Sort the merged array using Bubble Sort to maintain order. 4️⃣ Determine the median: If total length is even, return the average of the two middle elements. If odd, return the middle element directly. 🔥 Performance: ✅ Accepted on LeetCode ⚡ Runtime: 52 ms 💾 Memory: 48.81 MB 📊 Complexity: ⏱ Time: O((m + n)²) — due to bubble sort 💾 Space: O(m + n) — extra array used for merging #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Consistency #LearningInPublic #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