Day 97/100 Problem Statement : You are given the two integers, n and m and two integer arrays, hBars and vBars. The grid has n + 2 horizontal and m + 2 vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from 1. You can remove some of the bars in hBars from horizontal bars and some of the bars in vBars from vertical bars. Note that other bars are fixed and cannot be removed. Return an integer denoting the maximum area of a square-shaped hole in the grid, after removing some bars (possibly none). Input: n = 2, m = 1, hBars = [2,3], vBars = [2] Output: 4 Solution : https://lnkd.in/gJ4FkbK9 public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { Arrays.sort(hBars); Arrays.sort(vBars); int s = Math.min(maxSpan(hBars), maxSpan(vBars)); return s * s; } private int maxSpan(int[] bars) { int res = 1, streak = 1; for (int i = 1; i < bars.length; i++) { if (bars[i] - bars[i - 1] == 1) streak++; else streak = 1; res = Math.max(res, streak); } return ++res; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
Maximizing Square Hole Area in Grid
More Relevant Posts
-
🔥 Day 97/100 of Code – Subsets II: Backtracking with Duplicate Pruning! Today solved a power set problem with duplicate elements — a clean extension of the classic subsets problem: ✅ Problem 90: Subsets II Task: Generate all unique subsets from an array that may contain duplicates. Approach: Sort + backtracking with level-skip logic: Sort array to group duplicates At each recursion level, iterate from ind to end: Skip duplicates: if (i != ind && nums[i] == nums[i-1]) continue Include nums[i], recurse with i+1 Backtrack Key Insight: The condition i != ind ensures we only take the first occurrence of a duplicate at each recursion depth, preventing duplicate subsets across different branches. Complexity: O(2^n) time worst-case, but pruning avoids duplicate subset generation. A subtle but crucial tweak to standard subset backtracking — handles real-world duplicate data elegantly! 🔄📦 #100DaysOfCode #LeetCode #Java #Backtracking #Subsets #DFS #Algorithm
To view or add a comment, sign in
-
-
📁 File Handling 🌊Character streams deal with Unicode characters 🌍 👉 They are meant for text, not raw binary data like byte stream.| ✔️ FileWriter → can create a file if it doesn’t exist ✨ ❌ FileReader → never creates a file 👉 If file doesn’t exist → FileNotFoundException 🚫 Reading rules 📖 ✔️ read() returns -1 at end of file 🛑 ✔️ Correct pattern: while ((ch = reader.read()) != -1) 🔁 File deletion 🗑️ ✔️ file.delete() ✔️ Returns boolean (true / false) ❓ Why no exception? 👉 Because streams are irrelevant for delete ❌ Character streams CANNOT update content in the middle of a file ✔️ Same rule as byte streams Why? 🤔 👉 Files are linear 📏 👉 There is no “insert here” operation 👉 You can only read forward or write forward What “update” actually means in Java 🧠 There is ONLY one way 👇 1️⃣ Read entire file (FileReader) 📖 2️⃣ Modify content in memory (String / StringBuilder) 🧩 3️⃣ Rewrite entire file (FileWriter) ✍️ ✅ This is the only real update mechanism Append ≠ Update ⚠️ 👉 Files store bytes; FileReader interprets bytes as characters, FileInputStream does not. GitHub Link: https://lnkd.in/g9843mcC 🔖Frontlines EduTech (FLM) #Java #JavaIO #FileHandling #ByteStream #CharacterStream #FileInputStream #FileReader #Unicode #JVM #JavaConcepts #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #BackendDevelopment #Programming #Java #FileHandling #CharacterStreams #Unicode #FileReader #FileWriter #BackendConcepts #LearningInPublic
To view or add a comment, sign in
-
-
Day - 54 Copy List with Random Pointer The problem - A linked list has next and random pointers. Deep copy the list (create new nodes with same values and pointer relationships). Example : [[7,null],[13,0],[11,4],[10,2],[1,0]] → deep copied list Approach Used - •) Create HashMap<Node, Node> oldToNew. •) Traverse original list (curr = head) 1 - For each node, create new node with same value. 2 - Store mapping, oldToNew.put(curr, new Node(curr.val)). 3 - Move curr forward. •) Traverse original list again (curr = head) 1 - Set next, oldToNew.get(curr).next = oldToNew.get(curr.next). 2 - Set random, oldToNew.get(curr).random = oldToNew.get(curr.random). 3 - Move curr forward. •) Return oldToNew.get(head). Complexity - Time - O(n), two passes. Space - O(n), HashMap stores n mappings. Note - Use HashMap to store old→new node mapping. First pass creates nodes, second pass sets pointers #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 98/100 of Code – Permutations: In-Place Backtracking with Swapping! Today revisited the classic permutation problem using an elegant in-place swapping approach: ✅ Problem 46: Permutations Task: Generate all permutations of distinct integers. Approach: Recursive swapping with index tracking: Fix elements step-by-step by swapping them into position At level i, swap nums[i] with each nums[j] where j ≥ i Recurse to i+1, then backtrack by swapping back Base case: when i == nums.length, store current array state Key Insight: By swapping in-place, we avoid extra space for temporary lists and naturally generate permutations without duplicate checks (since elements are distinct). Complexity: O(n × n!) time, O(n) recursion depth — optimal for generating all permutations. A clean, memory-efficient backtracking technique — fundamental for combinatorial generation! 🔄🧩 #100DaysOfCode #LeetCode #Java #Backtracking #Permutations #DFS #Algorithm
To view or add a comment, sign in
-
-
Day - 65 Letter Combinations of Phone Number The problem - Given string of digits 2-9, return all possible letter combinations that the number could represent (like old phone keypads). Example : digits = "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"] Brute Force - Generate all combinations iteratively using nested loops - works but becomes unwieldy with variable input length. Approach Used - •)Create map, 2→"abc", 3→"def", 4→"ghi", 5→"jkl", 6→"mno", 7→"pqrs", 8→"tuv", 9→"wxyz" •) Handle edge case, if digits is null or empty, return empty list. •) Initialize, call backtrack(digits, 0, new StringBuilder(), res, map). •) Backtrack(digits, idx, comb, res, map), 1 - Base Condition, if idx == digits.length, add comb to res. 2 - Recursive case, get letters for current digit, String letters = map.get(digits.charAt(idx)). 3 - For each letter, append to comb, recurse with idx+1, backtrack(digits, idx + 1, comb, res, map). Remove last character, comb.deleteCharAt(comb.length() - 1). Complexity - Time - O(4^n × n), max 4 letters per digit, n to build each string. Space - O(n), recursion depth. Note - Use map for digit→letters. For each digit, try all its letters, recurse to next digit. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 15 – Static Array vs Dynamic Array (and why Arrays still rule in DSA) “Why learn static arrays when we already have ArrayList / dynamic arrays?” 🤔 => And today I realized this clearly while solving: 🧠 Problem: First Negative Number in every Window (size = K) This problem is solved efficiently using: ✅ Static Array ✅ Sliding Window ✅ Queue for tracking negatives Logic : private static List<Integer> findFirstNegativeNumInSubArray(int[] arr, int k) { List<Integer> result = new ArrayList<>(); Queue<Integer> queue = new LinkedList<>(); int left = 0; for (int right = 0; right < arr.length; right++) { // Add negative numbers to queue if (arr[right] < 0) { queue.offer(arr[right]); } // When window size is reached if (right - left + 1 == k) { // Add first negative or 0 result.add(queue.isEmpty() ? 0 : queue.peek()); // Remove element going out of window if (!queue.isEmpty() && arr[left] == queue.peek()) { queue.poll(); } left++; // slide window } } return result; } Dynamic arrays make life easy. Static arrays make you a strong problem solver. Master arrays → master DSA → master backend performance 💪 #Day15 #Java #Arrays #SlidingWindow #DSA #ProblemSolving #JavaDeveloper #CodingJourney #Consistency #Microservices
To view or add a comment, sign in
-
#100DaysOfLeetcode journey🚀 Day 5/100 — Mastering the Sliding Window!Today’s Problem: Longest Substring Without Repeating Characters (or similar Sliding Window variant)🔹 The Goal: After Day 4’s success with nested expansion, I wanted to push for maximum efficiency by reducing time complexity from $O(n^2)$ to $O(n)$. The objective was to find the maximum length of a valid window in a single pass through the data.🔹 The Insight: The "Sliding Window" is essentially a dynamic subarray that grows and shrinks based on a specific constraint. Instead of resetting the search for every index, I maintain a "memory" of the current window's state. When a violation occurs (like a duplicate character), I don't restart; I simply contract the window from the left until it's valid again.🔹 The Difficulty: The mental hurdle with Sliding Window is the "contracting" logic. You have to ensure that as the left pointer moves, you accurately update your frequency map or set to reflect the elements leaving the window. It requires keeping two pointers in perfect sync to avoid off-by-one errors.✨ Achievement: Achieved 100% Runtime efficiency by using a direct-address table (primitive int[128] array) instead of a HashMap. This minimized the overhead of auto-boxing and hashing, allowing the algorithm to run at the absolute speed limit of the JVM.🔍 Steps followed:✔ Two-Pointer Strategy: Implemented left and right pointers to define the boundaries of the active window.✔ Frequency Tracking: Used a fixed-size integer array to store the last seen positions of characters for $O(1)$ lookups.✔ Dynamic Resizing: As the right pointer expanded, if a duplicate was found, the left pointer was "jumped" to the index after the previous occurrence, instantly validating the window.✔ Global Maximum: Updated the maxLen at every iteration to capture the peak window size.🔧 Complexity Analysis:Time Complexity: $O(n)$ (Each element is visited by the pointers at most twice)Space Complexity: $O(k)$ (Where $k$ is the size of the character set, constant space)Five days of consistency! Moving from "it works" to "it works optimally" is where the real growth happens. 🛠️#Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #SlidingWindow #Optimization #Efficiency
To view or add a comment, sign in
-
-
Day - 56 Remove Nth Node From End of List The problem - Given the head of a linked list, remove the nth node from the end and return the head. Example : head = [1,2,3,4,5], n = 2 → [1,2,3,5] head = [1], n = 1 → [] head = [1,2], n = 1 → [1] Brute Force - Count total length, then calculate position from start, and remove, but time complexity would be O(n) with two traversals Approach Used - •) Create dummy node, temp = new ListNode(0, head). •) Initialize dum = temp, and head pointer. •) Move head pointer n steps ahead, for i from 0 to n-1, head = head.next. Now gap between dum and head is n nodes. •) Move both pointers until head reaches end, While (head != null), 1 - Move head forward, head = head.next. 2 - Move dum forward, dum = dum.next. (Now dum is at the node beforethe one to delete.) •) Delete the nth node, dum.next = dum.next.next. •) Return temp.next Complexity - Time - O(n), single traversal. Space - O(1), only pointers. Note - Use two pointers separated by n nodes. When the front pointer reaches the end, the back pointer is at the node before the one to delete. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
When I first learned Tree data structures in Java, I felt lost. Arrays were easy. Lists were predictable. Everything was linear. Then Trees showed up. 1 / \ 2 3 / \ / \ 4 5 6 7 I just don't know how to read this. If you’ve ever felt the same confusion, I wrote a detailed breakdown, starting from counting nodes, understanding levels, all the way to inOrder traversal. 👉 Read the full explanation on my website here: https://lnkd.in/g6kJjRTC #Java #DataStructures #BinaryTree #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
🔥 Day 96/100 of Code – Combination Sum II: Backtracking with Duplicate Handling! Today tackled a refined version of combination sum with no reuse and duplicate candidates — requiring careful pruning: ✅ Problem 40: Combination Sum II Task: Find all unique combinations (each candidate used once) that sum to target, with duplicates in input. Approach: Sort + backtracking with skip logic: Sort candidates to group duplicates At each step, iterate from ind to end: Skip duplicates: if (i > ind && nums[i] == nums[i-1]) continue Break early if nums[i] > target (pruning) Include nums[i], recurse with i+1 (no reuse) Backtrack Key Insight: Sorting lets us skip duplicate combinations elegantly. The condition i > ind ensures we skip duplicate values within the same recursion level but allow them across different levels. Complexity: O(2^n) worst-case, but pruning reduces search space significantly. A clean example of how sorting and careful duplicate skipping refine backtracking for real-world inputs! 🔄🔍 #100DaysOfCode #LeetCode #Java #Backtracking #DFS #Combinations #Algorithm #Day96
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