Day 24 of #100DaysOfCode I stared at this problem for 40 minutes trying every possible target value. Then one insight — borrowed from basic statistics — made it click instantly. 🧩 The Problem: Minimum Operations to Make a Uni-Value Grid (LeetCode 2033 — Medium) Given a 2D grid and a fixed step value x, transform every element to the same value using the minimum number of add/subtract operations. My first instinct? Try every possible target. Loop through everything. Classic overthinking. 😅 💡 The Key Insight — Why the Median? The median minimizes the sum of absolute differences. This is a well-known statistics fact — and it maps perfectly to this problem. Instead of brute-forcing every target, the strategy is simple: → Flatten the 2D grid into a 1D array → Sort it → Pick the middle element (median) as the target → Count total operations using the absolute difference divided by x No guessing. No unnecessary loops. Just math doing the heavy lifting. ⚠️ The Constraint Check Nobody Talks About Before applying any operations — check if all elements share the same remainder when divided by x. If they don't, it's mathematically impossible to make the grid uni-value. Return -1 immediately and save the computation entirely. This "fail fast" mindset is just as important as the algorithm itself. 📈 Complexity Breakdown → Flatten + Sort → O(n log n) → Single pass to count operations → O(n) → Space → O(n) for the flattened array Simple, clean, and efficient. 🧠 What This Problem Reinforced ✅ Greedy thinking with median optimization ✅ Handle impossible cases before computation — fail fast ✅ Transform 2D problems into simpler 1D forms ✅ Let math do the heavy lifting before writing a single loop The best solutions often come from asking: "What does math already know about this?" On to the next challenge 💪 👇 What's a problem where a simple insight saved you from overcomplicating things? Drop it in the comments — would love to learn from your experience! #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #CodingJourney #SoftwareEngineering #Programming
Minimum Operations to Make a Uni-Value Grid with Median Optimization
More Relevant Posts
-
🚀 Solved “Search Insert Position” using Binary Search on LeetCode! Today I worked on an interesting problem where the goal is to find the index of a target element in a sorted array. If the target is not present, we return the index where it should be inserted to maintain sorted order. 🔍 Approach: Instead of using a linear search (O(n)), I implemented an efficient Binary Search (O(log n)) approach. 💡 Key Learning: One important detail is calculating the middle index safely: mid = low + (high - low) / 2 This avoids potential integer overflow compared to (low + high) / 2 and ensures correct behavior even for large inputs. ⚙️ Logic: If target == arr[mid] → return mid If target > arr[mid] → search right half Else → search left half If not found → return ‘low’ as the correct insert position 📈 Result: Achieved 100% performance on LeetCode 🚀 This problem reinforced my understanding of: ✔ Binary Search fundamentals ✔ Edge case handling ✔ Writing optimized and safe code Looking forward to solving more problems and improving problem-solving skills! #LeetCode #BinarySearch #Java #DataStructures #Coding #ProblemSolving
To view or add a comment, sign in
-
-
Day 44- Ever wondered how one class can use another class without inheriting it? That’s exactly what the Has-A relationship is all about. Instead of making one class do everything, we let classes work together. 🔹 What is Has-A relationship? Has-A means: One class contains another class as a part of it. It doesn’t inherit behavior, it simply uses another object to perform tasks. This helps in building clean and modular code. 🔹 Let’s understand with a simple example class Test { void play() { System.out.println("Executing play()......"); } } class Example { Test ref; Example(Test ref) { this.ref = ref; } } public class MainClass2 { public static void main(String[] args) { Test t1 = new Test(); Example e1 = new Example(t1); e1.ref.play(); } } 🔹 What’s happening here? • A Test object is created • That object is passed into Example • Example stores it using a reference (ref) • Then Example uses it to call play() 🔹 Why this is Has-A? Because: 👉 Example HAS-A Test object 👉 It is not extending Test 👉 It is simply using Test’s functionality 🔹 Type of relationship here This is Aggregation (Weak Has-A) ✔ The Test object exists independently ✔ It is created outside and passed into Example ✔ Both classes are loosely connected 🔹 Why this matters Using Has-A relationship helps in: • Better code structure • Reusability of classes • Loose coupling • Real-world modelling Instead of writing one big class, we design systems where objects collaborate. #Java #OOP #ObjectOrientedProgramming #JavaProgramming #Coding #Programming #SoftwareDevelopment #Developer #LearningInPublic #TechLearning #ComputerScience #CodingJourney #CodeNewbie #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Day 56 of my DSA Journey Today, I worked on a Hard-level problem from LeetCode: 👉 Problem #4 – Median of Two Sorted Arrays (LeetCode) This problem is well-known for its complexity and is frequently asked in top product-based companies. 💡 What I focused on: Understanding the problem deeply instead of jumping directly to the optimal solution Implementing a merge + sort approach to build a clear foundation Applying the two-pointer technique to efficiently identify the median Handling both odd and even length cases carefully ⚙️ Approach Used: Merged both input arrays into a single array Sorted the combined array Used two pointers (i and j) moving towards the center Determined the median based on whether the length is odd or even 📈 Key Learning: Even though the optimal solution has a time complexity of O(log(min(m, n))), building a correct and intuitive approach first is crucial. It strengthens problem-solving skills and helps in understanding advanced techniques later. 🎯 Takeaway: Consistency and clarity in logic are more important than immediately writing the most optimized code. 🔥 Step by step, moving closer to mastering Data Structures & Algorithms. #DSA #LeetCode #ProblemSolving #Java #CodingJourney #PlacementPreparation #Consistency #Learning
To view or add a comment, sign in
-
-
Day 9/30 – Abstraction and Shortest Path in DAG Day 9 of the challenge focused on learning another important pillar of Object Oriented Programming and solving a graph problem based on shortest paths. Today’s learning was about hiding unnecessary complexity in code and using graph ordering to calculate minimum distances efficiently. MERN / OOP Concepts – Abstraction Today I learned about Abstraction, one of the core pillars of Object-Oriented Programming. What is Abstraction: • Abstraction means hiding internal implementation details and showing only essential functionality • It helps users interact with features without needing to know how everything works internally How it is achieved in Java: • Abstract classes • Interfaces Why it matters: • Reduces complexity • Improves code readability • Makes systems easier to maintain and extend • Focuses on what an object does instead of how it does it Real-world example: • When driving a car, we use steering, brakes, and accelerator • We do not need to understand the engine internals to drive it Key takeaway: • Show only what is necessary, hide the rest DSA – Shortest Path in DAG Today I solved Shortest Path in Directed Acyclic Graph (DAG). Approach: • Build graph using adjacency list with weights • Perform Topological Sort of all nodes • Initialize distance array with infinity • Start source node distance as 0 • Process nodes in topological order • Relax all outgoing edges to update shortest distances Key insight: • Since DAG has no cycles, topological order guarantees that each node is processed after its dependencies • This makes shortest path faster than Dijkstra in DAG cases Why this problem is important: • Combines Topological Sort with shortest path logic • Shows how graph structure can optimize solutions Time Complexity: O(V + E) Space Complexity: O(V + E) Takeaways • Abstraction helps simplify complex systems • Good software design hides unnecessary details • DAG problems often become easier using topological order • Choosing the right graph technique can greatly improve efficiency Day 9 completed. Concepts are getting deeper, and patterns are becoming more natural. #30DaysChallenge #OOP #Abstraction #Java #DSA #Graphs #ShortestPath #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 84 – DSA Journey | Maximum Depth of Binary Tree Continuing my daily DSA practice, today I focused on understanding tree depth and recursive problem solving. 📌 Problem Practiced: Maximum Depth of Binary Tree (LeetCode 104) 🔍 Problem Idea: Find the maximum depth (or height) of a binary tree — the number of nodes along the longest path from the root to a leaf node. 💡 Key Insight: The depth of a tree depends on its subtrees. At every node, we can recursively calculate the depth of left and right subtrees and take the maximum. 📌 Approach Used: • If the node is null → depth is 0 • Recursively calculate depth of left subtree • Recursively calculate depth of right subtree • Return 1 + max(left, right) 📌 Concepts Strengthened: • Binary tree traversal • Recursion • Divide and conquer approach • Tree height calculation ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(h) (recursion stack) 🔥 Today’s takeaway: Breaking problems into smaller subproblems using recursion makes complex tree problems much easier to handle. On to Day 85! 🚀 #Day84 #DSAJourney #LeetCode #BinaryTree #Recursion #Java #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Day 38 of My DSA Journey Today I solved LeetCode 152 – Maximum Product Subarray on LeetCode. 📌 Problem Given an integer array nums, find the contiguous subarray that has the largest product, and return that product. Example: Input: [2,3,-2,4] Output: 6 → subarray [2,3] 🧠 Approach – Dynamic Programming (Tracking Max & Min) This problem is tricky because of negative numbers. Key Idea: • At each index, we maintain: maxProduct → maximum product ending at current index minProduct → minimum product ending at current index 👉 Why min? Because a negative number can turn a small (negative) product into a large positive one. Steps I followed: • Initialize maxProduct, minProduct, and ans with the first element • Traverse the array from left to right • If the current number is negative → swap max and min • Update: maxProduct = max(current, current × maxProduct) minProduct = min(current, current × minProduct) • Update the final answer using maxProduct ⏱ Time Complexity: O(n) — Single pass through the array 📦 Space Complexity: O(1) — No extra space used 💡 Key Learnings ✔ Handling negative numbers in product problems ✔ Using dynamic programming with state tracking ✔ Understanding why tracking both max & min is important This is one of those problems that looks simple but tests deep understanding of edge cases 🚀 Consistency continues — leveling up every day 💪 #100DaysOfCode #DSA #DynamicProgramming #Arrays #LeetCode #Java #ProblemSolving #CodingJourney #DeveloperJourney #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 88 – DSA Journey | Binary Tree Postorder Traversal Continuing my daily DSA practice, today I tackled one of the trickier tree traversals using an iterative approach. 📌 Problem Practiced: Binary Tree Postorder Traversal (LeetCode 145) 🔍 Problem Idea: Traverse a binary tree in postorder — Left → Right → Root — and return the node values. 💡 Key Insight: Postorder traversal is not straightforward iteratively. A clever trick is to reverse a modified preorder traversal (Root → Right → Left) to achieve the correct order. 📌 Approach Used: • Use a stack to process nodes • Traverse in Root → Right → Left order • Insert elements at the beginning of the result list • This effectively reverses the order to get Left → Right → Root 📌 Concepts Strengthened: • Tree traversal (Postorder) • Stack usage • Iterative traversal tricks • Reversing traversal logic ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) 🔥 Today’s takeaway: Sometimes solving a problem becomes easier when you reverse the perspective — small tricks can simplify complex logic. On to Day 89! 🚀 #Day88 #DSAJourney #LeetCode #BinaryTree #Stack #Java #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
🚀 Day 75 — Slow & Fast Pointer (Happy Number Detection) Extending the slow‑fast pointer pattern beyond linked lists — today I applied it to a mathematical problem involving cycles. 📌 Problem Solved: - LeetCode 202 – Happy Number 🧠 Key Learnings: 1️⃣ The Problem in a Nutshell A number is happy if repeatedly replacing it with the sum of squares of its digits eventually reaches 1. If it enters a cycle that doesn’t include 1, it’s unhappy. 2️⃣ Why Slow‑Fast Pointer Works - The sequence of numbers (n → sum of squares of digits → ...) will eventually either reach 1 or enter a cycle. - This is exactly like detecting a cycle in a linked list — except the “next” is defined mathematically. - Slow moves one step: `slow = sq(slow)` - Fast moves two steps: `fast = sq(sq(fast))` - If they meet at a value other than 1 → cycle exists → unhappy number. - If fast reaches 1 → happy number. 3️⃣ The sq() Helper Computes sum of squares of digits. Clean and reusable. 4️⃣ Edge Cases - n = 1 → returns true immediately (loop condition `fast != 1` fails, returns true). - Numbers like 2, 3, 4 eventually cycle (4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4). 💡 Takeaway: The slow‑fast pointer pattern isn’t just for linked lists — it’s a general cycle detection tool that works for any sequence with a deterministic “next” step. Recognizing this abstraction is what makes a great problem solver. No guilt about past breaks — just one problem at a time, one pattern at a time. #DSA #SlowFastPointer #HappyNumber #CycleDetection #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 54 of My LeetCode Journey 🔍 Problem: Find the Index of the First Occurrence in a String Today’s problem focused on searching for a substring inside a string — a very common concept in interviews and real-world applications like text processing and search engines. 💡 Key Idea: We compare the substring (needle) with every possible starting position in the main string (haystack) until we find a match. 🧠 What I Learned: How string matching works internally Importance of boundary conditions (like empty strings) Difference between brute-force and optimized approaches Why built-in methods like indexOf() are efficient ⚡ Approaches: Using built-in method (indexOf) – simple and efficient Manual iteration (brute force) – helps understand logic deeply 📈 Time Complexity: O(n * m) for brute-force approach 🔥 Takeaway: Even simple problems can teach core fundamentals. Mastering these basics builds a strong foundation for advanced algorithms like KMP. #Day54 #LeetCode #Java #DataStructures #CodingJourney #Programming #InterviewPreparation
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