📅 Day 53 of #100DaysOfLeetCode Problem: 840. Magic Squares In Grid Difficulty: Medium 🔍 Problem Insight A 3×3 magic square must: Contain distinct numbers from 1 to 9 Have the same sum for all rows, columns, and both diagonals The task is to count how many such 3×3 subgrids exist inside a given grid. 💡 Key Observations Magic squares are strictly limited to 3×3 Any number outside 1–9 immediately invalidates the square Duplicate values break the magic condition Grid size is small, allowing safe sliding-window checks ⚙️ Approach Slide a 3×3 window across the grid For each window: Use a HashSet to ensure values are unique and within 1–9 Compute the target sum from the first row Validate: All rows All columns Both diagonals Count all valid magic squares ⏱️ Complexity Time: O(m × n) Space: O(1) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
Counting 3x3 Magic Squares in a Grid
More Relevant Posts
-
Day 13/100 – LeetCode Challenge ✅ Problem: #368 Largest Divisible Subset Difficulty: Medium Language: Java Approach: Dynamic Programming with Path Reconstruction Time Complexity: O(n²) Space Complexity: O(n) Key Insight: After sorting, a divisible subset maintains divisibility chain: If nums[i] % nums[j] == 0, extend subset from j to i. Track both DP count and previous index for reconstruction. Solution Brief: Sorted array and initialized dp[i]=1, prev[i]=-1. Nested loops to build longest divisible chain, storing parent indices. Reconstructed subset by backtracking from maxi using prev array. Finding structured subsets with divisibility chains #LeetCode #Day13 #100DaysOfCode #DynamicProgramming #Java #Algorithm #CodingChallenge #ProblemSolving #LargestDivisibleSubset #MediumProblem #PathReconstruction #Subset #DSA #Array
To view or add a comment, sign in
-
-
Day 33/100 – LeetCode Challenge ✅ Problem: #1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold Difficulty: Medium Language: Java Approach: Prefix Sum + Binary Search on Square Size Time Complexity: O(m × n × log(min(m, n))) Space Complexity: O(m × n) Key Insight: Use 2D prefix sum to quickly compute sum of any square submatrix in O(1). For each cell, binary search the maximum square side length starting at that cell with sum ≤ threshold. Solution Brief: Built prefix sum matrix psum for O(1) submatrix sum queries. For each possible starting cell, used binary search to find largest valid square. Tracked global maximum side length across all positions. Optimizing submatrix queries with prefix sum. #LeetCode #Day33 #100DaysOfCode #BinarySearch #Java #Algorithm #CodingChallenge #ProblemSolving #MaxSquareSide #MediumProblem #PrefixSum #Matrix #Optimization #DSA
To view or add a comment, sign in
-
-
🚀 DSA Series – Day 29 📌 Problem: Find the Duplicate Number (LeetCode) Today I worked on a classic array problem where the goal is to find the single duplicate number in an array containing n+1 integers from 1 to n. 🧠 What I learned Instead of sorting or nested loops, we can use a frequency array to track how many times each number appears. If a number appears more than once, that is our duplicate. 💡 My Approach -Create an extra array to store counts -Traverse the input array and increase the count -Scan the count array to find the value with frequency > 1 ⏱ Complexity Time: O(n) Space: O(n) #DSA #LeetCode #Java #ProblemSolving
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
-
-
Day 16/100 – LeetCode Challenge ✅ Problem: #1547 Minimum Cost to Cut a Stick Difficulty: Hard Language: Java Approach: Dynamic Programming (Interval DP) Time Complexity: O(m³) where m = cuts.length Space Complexity: O(m²) Key Insight: Transform cuts problem into interval partitioning: Sort cuts and add boundaries 0 and n dp[i][j] = min cost to cut stick between cuts[i] and cuts[j] Cost for cutting at k = cuts[j] - cuts[i] + dp[i][k] + dp[k][j] Solution Brief: Created extended cuts array with endpoints. Used interval DP: for each length, computed min cost by trying every cut point. Final answer: dp[0][m+1] (entire stick). Mastering interval partitioning and cost optimization #LeetCode #Day16 #100DaysOfCode #DynamicProgramming #Java #Algorithm #CodingChallenge #ProblemSolving #MinimumCostCutStick #HardProblem #IntervalDP #Optimization #DSA #Partitioning
To view or add a comment, sign in
-
-
Day 39/100 – LeetCode Challenge ✅ Problem: #1984 Minimum Difference Between Highest and Lowest of K Scores Difficulty: Easy Language: Java Approach: Sorting + Sliding Window Time Complexity: O(n log n) Space Complexity: O(1) Key Insight: After sorting, the minimum range in k elements must come from consecutive elements in sorted order. Sliding window of size k finds the minimum difference between first and last element in window. Solution Brief: Sorted the array to bring close values together. Initialized answer with first k elements. Slided window across array, updating minimum difference. Finding minimal range in sorted array with sliding window #LeetCode #Day39 #100DaysOfCode #Sorting #SlidingWindow #Java #Algorithm #CodingChallenge #ProblemSolving #MinimumDifference #EasyProblem #Array #Optimization #DSA
To view or add a comment, sign in
-
-
#200DaysOfCode – Day 109 Problem: LeetCode 17 – Letter Combinations of a Phone Number Task:- Given a string of digits (2–9), return all possible letter combinations based on the phone keypad mapping. Example: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] My Approach: Used a mapping array to store digit-to-letter relationships. Applied backtracking to build combinations character by character. Once the current combination length matched the input length, added it to the result list. Used StringBuilder for efficient string manipulation. Time Complexity: O(4ⁿ) Space Complexity: O(n) (recursive stack) Backtracking is a powerful technique when dealing with combinations and permutations. Breaking the problem into smaller recursive steps makes complex logic much easier to handle. #takeUforward #200DaysOfCode #LeetCode #Java #Backtracking #Recursion #ProblemSolving #DSA #CodeNewbie #Consistency #LearnEveryDay
To view or add a comment, sign in
-
-
Day 32 | GFG 160 Solved K-th Element of Two Sorted Arrays using Binary Search on Partitions. Logic Breakdown: Applied binary search on the smaller array Partitioned both arrays so that the left side has exactly k elements Checked the conditions: leftA ≤ rightB leftB ≤ rightA As soon as a valid partition is found, the answer is max(leftA, leftB) Time Complexity: O(log(min(n, m))) Much faster than merging both arrays. #Day32 #GFG160 #DSA #BinarySearch #KthElement #Java #Consistency #CodingJourney 🚀
To view or add a comment, sign in
-
-
Day 41/100 – LeetCode Challenge ✅ Problem: #130 Surrounded Regions Difficulty: Medium Language: Java Approach: DFS from Boundary + In-Place Modification Time Complexity: O(m × n) Space Complexity: O(m × n) for recursion stack Key Insight: Only 'O's connected to boundary cannot be surrounded. Mark all boundary-connected 'O's via DFS, then convert remaining 'O's to 'X'. Solution Brief: Traversed all four boundaries, starting DFS from each 'O'. Used vis[][] to mark connected 'O's reachable from boundary. Final pass: convert unvisited 'O's (surrounded) to 'X'. Smart boundary-based approach for region detection #LeetCode #Day41 #100DaysOfCode #DFS #Java #Algorithm #CodingChallenge #ProblemSolving #SurroundedRegions #MediumProblem #Matrix #Graph #BoundaryTraversal #DSA
To view or add a comment, sign in
-
-
LeetCode Practice - 944. Delete Columns to Make Sorted 🧠 Problem Idea ✅ You are given n strings, all of the same length. ✅ Imagine them written one below another like a grid. Example: cba daf ghi We check column by column. Column 0 → c d g → sorted ✅ Column 1 → b a h → NOT sorted ❌ Column 2 → a f i → sorted ✅ So we delete column 1 → answer = 1 🛠️ Key Observation ✅ A column is sorted if characters do not decrease from top to bottom. That means: 📌 strs[0][col] <= strs[1][col] <= strs[2][col] <= ... ✅ If any pair breaks this rule, that column must be deleted. 🚀 Algorithm 🔷 Take number of rows n 🔷 Take the n strings 🔷 For each column 🔷 Compare every row with the next row 🔷 If upperRowChar > lowerRowChar, mark it as invalid 🔷 Count how many columns are invalid #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
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