🚀 Day 49 of My Coding Journey Today I solved an interesting problem: Row with Maximum 1s in a Binary Matrix 🧠 Problem Insight: Given a 2D binary matrix where each row is sorted (0s first, then 1s), the goal is to find the index of the first row that contains the maximum number of 1s. ⚡ My Approach: At first, I thought of a brute force solution by counting 1s in every row. It works, but it's not efficient. Then I realized an important property: 👉 Since each row is sorted, once we find the first 1, all elements to the right are also 1. So instead of checking every element: Start from the top-right corner Move left if you find 1 Move down if you find 0 This reduces the time complexity to O(n + m) 🚀 💡 Key Learning: Understanding the structure of the data (sorted rows) can help optimize the solution drastically. 📌 Result: Successfully found the row index with maximum 1s efficiently. Every day, I’m getting better at recognizing patterns and optimizing solutions 💪 #Day49 #CodingJourney #Java #ProblemSolving #DataStructures #Algorithms #Learning #Consistency My way ===== // User function Template for Java class Solution { public int rowWithMax1s(int arr[][]) { int c=0,l=0,a=0; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { if(arr[i][j]==1) { c++; } } if(c>l) { l=c; a=i; } c=0; } if(l>0) { return a; } else { return -1; } } }
Optimizing Row with Maximum 1s in Binary Matrix
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
🚀 Day 18 / 100 Days of Java 💻 Today was all about going deeper into one of the most fundamental topics in programming — Arrays. Even though arrays seem simple at first, they are the backbone of many advanced data structures and algorithms. Here’s what I worked on today 👇 🔹 Understanding Arrays Learned how arrays are represented in memory and why they allow fast access using indexing. This helped me clearly understand how data is stored and retrieved efficiently. 🔹 Finding Maximum & Minimum Elements Practiced iterating through an array to identify the largest and smallest values — a simple yet powerful concept used in many real-world problems. 🔹 Finding the Third Largest Element This pushed me to think beyond basics and handle edge cases like duplicates and ordering without relying completely on sorting. 🔹 Searching an Element in Array Explored linear search and understood where it works best. Also got a glimpse of how search efficiency matters when data grows. 🔹 Finding Missing Number Solved problems using both brute force and optimized approaches. This improved my understanding of patterns and mathematical logic. 🔹 Finding Repeating Elements Learned different techniques to detect duplicates — from basic loops to more optimized methods using extra space. 💡 Key Learnings from Today: ✔ Arrays are not just beginner topics — they are the foundation of problem solving ✔ Writing clean logic is more important than jumping to complex solutions ✔ Edge cases (duplicates, boundaries, etc.) matter a lot ✔ There’s always a better (optimized) way to solve a problem 🔥 Reflection: Every day I realize that consistency beats intensity. Even small concepts, when practiced deeply, build strong problem-solving skills over time. 📈 Slowly but surely becoming better than yesterday. Let’s keep building, learning, and growing 💪 #Java #DSA #100DaysOfCode #CodingJourney #LearningInPublic #DeveloperLife #Programmer #CodingLife #SoftwareEngineering #ComputerScience #TechJourney #ProblemSolving #Algorithms #DataStructures #JavaDeveloper #CodeDaily #Consistency #GrowthMindset #SelfImprovement #StudentLife #EngineeringStudent #FutureEngineer #CodeNewbie #KeepLearning #BuildInPublic #Motivation #Discipline #DailyProgress #NeverGiveUp
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
-
-
🏗️ Scaling Up: Moving from Scripts to Systems As my Python projects grow, I’m learning that writing code that works is only half the battle. Writing code that is maintainable is where the real skill lies. I’ve started refactoring my automation scripts by breaking them down into reusable functions. Here’s why this shift is a game-changer: ♻️ Reusability (DRY - Don't Repeat Yourself) Instead of copying and pasting logic, I can write a function once and call it whenever I need it. It makes the codebase smaller and much easier to update. 📖 Readability By abstracting complex logic into functions with clear names like clean_data() or export_to_excel(), my main execution flow now reads like a story rather than a wall of text. Anyone (including my future self) can understand the logic at a glance. 🧪 Testability Organizing code into functions allows me to test individual "units" of logic in isolation. If something breaks, I know exactly which function is responsible, making debugging significantly faster. The Evolution: Level 1: Write a long script that runs top-to-bottom. Level 2: Organize logic into functions for better flow. Level 3: Move functions into separate modules for a professional project structure. I’m currently at Level 2 and feeling the difference in how I approach problem-solving! 💻 #PythonProgramming #CleanCode #SoftwareDevelopment #LearningToCode #CodeRefactoring #TechCommunity
To view or add a comment, sign in
-
🚀 Day 26 – Mastering Polymorphism (OOP Made Simple) Today I learned one of the most powerful concepts in OOP — Polymorphism (Many Forms). 👉 Definition: One method call can perform different actions depending on the object. Example: ref.takeOff() ✔ CargoPlane ✔ PassengerPlane ✔ FighterPlane Same method → Different behavior 🔥 ✈️ Plane Example (Real Understanding) We have a parent class Plane with methods: takeOff() fly() land() Child classes override these methods: CargoPlane PassengerPlane FighterPlane Each plane behaves differently 👇 🔴 Tight Coupling (Not Good) CargoPlane cp = new CargoPlane(); cp.takeOff(); ❌ No flexibility ❌ No real polymorphism 🟢 Loose Coupling (Best Practice) Plane ref = new CargoPlane(); ref.takeOff(); ✔ Flexibility ✔ Polymorphism achieved 🔼 Upcasting Child → Parent Plane ref = new CargoPlane(); 🔽 Downcasting Parent → Child ((CargoPlane) ref).carryCargo(); 📌 Important Rule Using Parent Reference: ✔ Can call inherited methods ✔ Can call overridden methods ❌ Cannot call specialized methods 🏢 Code Optimization Example class Airport { void permit(Plane ref) { ref.takeOff(); ref.fly(); ref.land(); } } Usage: a.permit(new CargoPlane()); a.permit(new PassengerPlane()); a.permit(new FighterPlane()); ✔ Same method works for all ✔ Less code, more power 💯 🎯 Advantages of Polymorphism ✅ Code Reduction ✅ Code Flexibility ✅ Reusability 🧠 Easy Memory Trick ✔ Child → Parent = Upcasting ✔ Parent → Child = Downcasting ✔ Tight Coupling = Same type reference + object ✔ Loose Coupling = Parent reference + child object 💡 Final Thought: "Write code once, use it many ways" — that’s the real power of Polymorphism. #Java #OOP #Polymorphism #CodingJourney #LearningInPublic #SoftwareEngineering #Day26
To view or add a comment, sign in
-
-
🚀 Day 49 of My Coding Journey Today I solved my second problem of the day: 👉 Triplet Sum Problem 🧠 Problem: Given an array and a target value, determine whether there exists a triplet whose sum equals the target. 💡 Example: arr = [1, 4, 45, 6, 10, 8], target = 13 ✔️ Output: true (Triplet: 1, 4, 8) ⚡ My Approach: At first, I considered the brute force method (checking all combinations), but that would take O(n³) time ❌ Then I optimized it using: 👉 Sorting + Two Pointer Technique 🔹 Steps: Sort the array Fix one element Use two pointers (left & right) to find the remaining sum ⏱️ Time Complexity: O(n²) ✅ 💡 Key Learning: Transforming a 3Sum problem into a 2Sum problem makes it much more efficient. 📈 Progress: This is my second problem on Day 49, and I’m improving my understanding of patterns like Two Pointer and optimization techniques. Small improvements every day lead to big results 💪 #Day49 #CodingJourney #Java #DSA #ProblemSolving #Consistency #Learning My way ===== class Solution { public boolean hasTripletSum(int arr[], int target) { int sum=0; Arrays.sort(arr); for(int i=0;i<arr.length;i++) { int left=i+1; int right=arr.length-1; while(left<right) { sum=arr[i]+arr[left]+arr[right]; if(sum==target) { return true; } else if(sum<target) { left++; } else { right--; } } } return false; } }
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
-
-
Headline: Deepening my expertise in Object-Oriented Programming! 🚀 I’m excited to share that I’ve been diving deep into the core pillars of Object-Oriented Programming (OOP), specifically focusing on Inheritance and Polymorphism. Understanding how to write reusable, scalable, and efficient code is essential for any software engineer. To solidify my concepts, I implemented these principles using both C++ and Python, comparing how each language handles method overriding and dynamic polymorphism. Key Takeaways from my recent study: Inheritance: Building robust hierarchies and reusing code effectively. Polymorphism: Mastering how a single interface can represent different underlying forms (Data types). Implementation: Exploring the nuances between C++ (Static/Runtime) and Python (Dynamic) approaches. Software engineering is a journey of continuous learning, and I’m enjoying every bit of the process. I’m looking forward to applying these concepts in more complex, real-world projects. I'd love to hear from my network—what’s your favorite OOP principle or a tip for mastering complex architectures? #SoftwareEngineering #OOP #ObjectOrientedProgramming #CPP #Python #CodingJourney #Polymorphism #ContinuousLearning #TechCommunity #KIU
To view or add a comment, sign in
-
-
🚀 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 4 of 50 Days Coding Challenge Today I solved a problem on Hashing Pattern 🔹 Problem: Two Sum 🔹 Approach: First tried brute force using nested loops (checking all pairs) Then optimized using HashMap (Hashing concept) to reduce time complexity 🔹 Key Learning: Instead of checking every pair, we can store values and directly check if the required complement exists. This reduces time complexity from O(n²) → O(n) 🚀 Also learned an important concept: 👉 need = target - current element 🔹 Time Complexity: O(n) 🔹 Code (Java): import java.util.*; class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int need = target - nums[i]; if(map.containsKey(need)) { return new int[]{map.get(need), i}; } map.put(nums[i], i); } return new int[]{-1, -1}; } } 💡 Consistency > Motivation #coding #leetcode #100DaysOfCode #java #programming #dsa #learning #hashmap
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