Hello Everyone, Day 16 / #100DaysOfCode LeetCode 2975 — Maximum Square Area by Removing Fences From a Field (Medium) Problem: You’re given a large rectangular field divided by horizontal and vertical fences. Some fences can be removed (boundary fences cannot). The goal is to form the largest possible square area by removing fences and return its area modulo 10^9 + 7. Key Insight: A square is possible only if the horizontal gap equals the vertical gap. So the problem reduces to: 1. Find all possible distances between pairs of horizontal fences. 2. Find all possible distances between pairs of vertical fences. 3. The largest common distance between the two determines the side of the square. Approach: - Add boundary fences (1 and m / n). - Sort fence positions. - Compute all possible differences between fence pairs. - Store horizontal differences in a set. - Iterate vertical differences and pick the maximum one that also exists in the horizontal set. - Square the side length and apply modulo. Why this works: Removing fences merges segments. Any square formed must span the same distance horizontally and vertically, so intersecting the two distance sets guarantees validity. Complexity: - Time: O(n^2+m^2) - Space: O(n^2) #Leetcode #DSA #Java
Max Square Area by Removing Fences in a Field
More Relevant Posts
-
Day 24 / #100DaysOfCode LeetCode 1877 — Minimize Maximum Pair Sum in Array (Medium) Problem (short): Given an array of even length, pair up all elements such that the maximum pair sum is minimized. Each element must be used exactly once. Key Insight: - To minimize the maximum pair sum, we must balance extremes. - Pairing large numbers together increases the maximum. - Pairing small numbers together wastes the chance to offset large values. So the optimal strategy is: - Sort the array - Pair the smallest with the largest, second smallest with second largest, and so on - Track the maximum among these pair sums This greedy pairing ensures no pair becomes unnecessarily large. Approach: 1. Sort the array 2. Use two pointers from both ends 3. For each pair, compute sum and update the maximum - Time Complexity: O(n log n) - Space Complexity: O(1) (ignoring sort space) #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
Hello Everyone, Day 20 / #100DaysOfCode LeetCode 3314 — Construct the Minimum Bitwise Array I (Easy) Problem (in short): You’re given an array nums of prime integers. Construct an array ans such that for every index i: ans[i] OR (ans[i] + 1) = nums[i] And among all valid choices, minimize ans[i]. If it’s impossible, return -1 for that index. Key Observation: For any number x: x OR (x + 1) turns all trailing 0s in x into 1s until the first 1 bit blocks the carry. So to reach a given prime p, x must: - Have all bits set where p has 1s - Except exactly one bit, which is flipped to allow (x + 1) to complete the OR Why some values are impossible: - If p has only one set bit (e.g., 2 → 10₂), - there’s no smaller x such that: x OR (x + 1) = p So the answer is -1. Minimization Strategy: To get the smallest possible x, we: - Start from x = p - 1 - Remove the lowest set bit from p - This guarantees (x | (x + 1)) = p while keeping x minimal Implementation-wise, this boils down to bit-walking using powers of two. Complexity: - Time: O(n · log(max(nums))) - Space: O(n) #Leetcode #DSA #Java
To view or add a comment, sign in
-
-
✅Day 67/75 – String Compression (In-Place) 📌 Problem Statement Given an array of characters chars, compress it using the following rules: For each group of consecutive repeating characters: 💠 If the group length is 1, keep the character as it is 💠If the group length is greater than 1, store the character followed by its count The compressed result must be stored in the same array Return the new length of the compressed array Use only constant extra space 📌 Example 🔺 Input: chars = ["a","a","b","b","c","c","c"] 🔺Output: 6 💡Approach 🔺Use two pointers: 💠i → traverse the array 💠j → track the position to write compressed characters 🔺Maintain a count of consecutive characters 🔺When the current character changes: 💠 Write the previous character 💠Write the count (if greater than 1) 🔺Handle the last group after the loop 🔺Convert counts ≥ 10 into multiple characters using String.valueOf(count) This ensures in-place compression with no extra space. ⏱️ Complexity Analysis 🔺Time : O(n) 🔺Space : O(1) #Day67 #75DaysChallenge #DSA #Java #LeetCode #StringManipulation #ProblemSolving
To view or add a comment, sign in
-
-
📘 LeetCode Daily — Balanced Binary Tree Checked tree balance by recursively comparing left and right subtree heights at every node. The solution worked, but it clearly showed how repeated height calculations increase time complexity—an important reminder that correct logic isn’t always optimal logic. Solid recursion practice and a good lead-in to optimization. #LeetCode #BinaryTree #Recursion #DSA #Java
To view or add a comment, sign in
-
-
Factory Pattern — Centralize Object Creation The Factory Pattern helps avoid scattered new statements by centralizing object creation logic. Instead of directly creating objects: Delegate creation to a factory Let the factory decide which implementation to return This makes the code: ✔ Easier to extend ✔ Cleaner to maintain ✔ Open for extension, closed for modification Create objects without exposing instantiation logic. #FactoryPattern #DesignPatterns #CleanCode #OOP #SoftwareArchitecture #DotNet #Java #BackendDevelopment
To view or add a comment, sign in
-
-
Adding Two Numbers :- The goal was to add two numbers represented as arrays and return the result as a new array. Approach Used : 1) Initialize two pointers Started from the last index of both arrays to simulate manual addition from right to left. 2) Use a carry variable Maintained a carry variable to handle cases where the sum of digits exceeds 9. 3) Handle unequal lengths safely If one array finishes earlier, treated its value as 0 using conditional logic. 4) Calculate sum and carry At each step: • sum = digit1 + digit2 + carry • store sum % 10 in result • update carry = sum / 10 5) Store result dynamically Used ArrayList to store digits since result size may vary. 6) Reverse the result Since digits were added from right to left, reversed the list to get the correct final order. This approach ensures efficient handling of carry and works for arrays of different lengths. Time Complexity: O(n) Space Complexity: O(n) #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
-
-
📘 LeetCode Daily — Balance a Binary Search Tree Solved this by first using inorder traversal to convert the BST into a sorted list, then reconstructing the tree from the middle element to ensure balance. This approach clearly showed how traversal order captures structure and how choosing the midpoint at each step naturally leads to a height-balanced tree. A neat example of combining traversal + divide-and-conquer. #LeetCode #BinarySearchTree #InorderTraversal #DivideAndConquer #DSA #Java
To view or add a comment, sign in
-
-
🚀 Day 61 of #100DaysOfCode Solved LeetCode Problem #1292 – Maximum Side Length of a Square with Sum ≤ Threshold 🟦 This problem revolved around efficiently finding the largest possible square submatrix whose total sum does not exceed a given threshold. A great mix of 2D prefix sums and greedy expansion. Key Learnings: -> Built a 2D prefix sum matrix to compute submatrix sums in O(1) -> Used incremental square expansion to avoid unnecessary recomputation -> Learned how prefix sums simplify range-sum constraints in grids -> Balanced correctness with performance for tight constraints Language Used: Java -> Runtime: 5 ms (Beats 99.49%) -> Memory: 57.82 MB (Beats 27.92%) Another day, another step forward in mastering matrix-based DP and prefix sum techniques 🚀 #LeetCode #Java #PrefixSum #DynamicProgramming #Matrix #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Finished the code-based part of the Loops module by comparing different loop structures. The logic stayed the same, but the control flow changed. // for loop for (int i = 1; i <= 5; i++) { System.out.print(i + " "); } // while loop int i = 1; while (i <= 5) { System.out.print(i + " "); i++; } // do-while loop int j = 1; do { System.out.print(j + " "); j++; } while (j <= 5); What this comparison made clear: - for is best when the number of iterations is known - while fits when the loop depends on a condition - do-while guarantees at least one execution - choosing the right loop improves readability, not just correctness This felt like a good way to close the practical part of loops. #Java #Loops #LearningInPublic #Beginner #DSA
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