I solved LeetCode 42: Trapping Rain Water in Java, and it turned out to be one of those problems that looks straightforward at first but hides deep lessons in algorithm design and optimization. The problem asks you to calculate how much water can be trapped between bars of different heights after it rains. It sounds simple, but when you try to implement it, you realize how easily brute-force approaches break down. My initial solution used nested loops to check how much water could be trapped at every index. It worked but ran with O(n²) time complexity, which quickly became inefficient for large inputs. That is when I shifted toward precomputation. The key idea is to figure out how much water each bar can hold by knowing the tallest bar to its left and right. Once that information is known, the amount of trapped water at any position is simply the minimum of those two maximum heights minus the height of the bar itself. To make this efficient, I created two arrays: maxLeft[i] stores the tallest bar to the left of index i. maxRight[i] stores the tallest bar to the right of index i. This approach brought the time complexity down to O(n) while keeping the logic simple and elegant. This problem taught me that performance improvements often come from rethinking the way you process information. Precomputation, caching, and avoiding repetitive operations are not just algorithmic tricks. They are the same concepts that drive efficiency in backend engineering, database optimization, and system design. In many ways, this problem reflects real-world engineering. It is not about how fast you can write code, but how effectively you can anticipate what the system will need before it needs it. That mindset is what separates good developers from great ones. What is one problem that helped you truly understand the balance between simplicity and optimization? #Java #Programming #SoftwareDevelopment #ProblemSolving #Algorithms #Coding #DSA #LeetCode #Engineering #SystemDesign
Solved LeetCode 42: Trapping Rain Water in Java with O(n) complexity
More Relevant Posts
-
✨ Don’t Use the ELSE Keyword — Simplifying Logic and Improving Readability 💡 One of the most interesting rules from Object Calisthenics is: “Don’t use the ELSE keyword.” At first glance, it seems radical — after all, else is a fundamental part of most programming languages. But when we stop using it, we start writing more linear, readable, and intentional code. In Java, this principle pushes us to design methods that express decisions clearly, avoiding nested logic and long conditional chains. Instead of focusing on what happens otherwise, we focus on the main flow — and that changes everything. 🤔 Why avoid else? ❌ Nested complexity: Each else adds one more level of indentation, making it harder to follow the method’s logic. ❌ Blurry intent: When if and else blocks both contain logic, it becomes harder to see the “happy path.” ❌ Difficult evolution: As rules grow, new else if statements quickly create a tangle of conditions. 🚀 What improves when you remove it? ✨ Simpler flow: By handling edge cases early (using guard clauses), the main path remains clean and focused. ✨ Better readability: The method reads like a short story — straightforward, without mental jumps. ✨ More maintainable code: Fewer nested blocks mean fewer bugs and easier refactoring. #Java #CleanCode #ObjectCalisthenics #Refactoring #CodeQuality #SoftwareDesign #SpringBoot
To view or add a comment, sign in
-
-
💡 LeetCode 3110 – Score of a String 💡 Today, I solved LeetCode Problem #3110: Score of a String, a neat little challenge that emphasizes understanding of ASCII values and absolute differences in Java strings. 🔠✨ 🧩 Problem Overview: You’re given a string s. The score of the string is defined as the sum of the absolute differences between the ASCII values of consecutive characters. Return the total score. 👉 Example: Input → "hello" Output → 13 Explanation → |'e'-'h'| + |'l'-'e'| + |'l'-'l'| + |'o'-'l'| = 3 + 7 + 0 + 3 = 13 💡 Approach: 1️⃣ Initialize a variable sum to store the total score. 2️⃣ Traverse the string from index 1 to end. 3️⃣ For each pair of consecutive characters, find their ASCII difference using Math.abs(). 4️⃣ Add the difference to sum and return it. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the string. ✅ Space Complexity: O(1) — Constant extra space. ✨ Key Takeaways: Strengthened understanding of character encoding and ASCII values. Reinforced clean looping logic and mathematical precision in Java. A great example of how simplicity can elegantly solve a real problem. 🌱 Reflection: Even the smallest coding challenges help sharpen attention to detail — from understanding data types to leveraging built-in functions effectively. Consistency is what transforms learning into mastery. 🚀 #LeetCode #3110 #Java #StringManipulation #ASCII #ProblemSolving #DSA #CodingJourney #CleanCode #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
Problem 27 : LeetCode 🎯 LeetCode Problem #645 Solved — Set Mismatch (Cyclic Sort Approach) 🧩 Today, I solved another interesting LeetCode Easy problem — “Set Mismatch”, which deepened my understanding of in-place sorting and index mapping using the Cyclic Sort technique. 🔍 Problem Overview Given an integer array nums where numbers are supposed to be from 1 to n, one number is duplicated, and one number is missing. The task: Find both numbers using O(n) time and O(1) space. 💡 My Approach — Cyclic Sort Technique I treated the array like a self-mapping structure where each number x should ideally be placed at index x - 1. If the current element isn’t in its correct place and its target isn’t already filled, I swap it. After the array is sorted in place, any index i where arr[i] != i + 1 indicates: arr[i] → the duplicate number i + 1 → the missing number ⚙️ Results ✅ Runtime: 3 ms — Beats 79.76% of Java submissions ✅ Memory: 47.45 MB — Beats 6.28% of submissions ✅ Complexity: O(n) time | O(1) space ✅ Status: Accepted ✅ (All 49 test cases passed) 🧩 Tech Stack Java | Cyclic Sort | Array Manipulation | In-Place Algorithm | DSA Another problem that reinforces my confidence in index-based logic and memory-efficient coding patterns — vital skills for backend and system optimization. #LeetCode #Java #ProblemSolving #CyclicSort #DataStructures #Algorithms #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Question Url : https://lnkd.in/dixwjFE3
To view or add a comment, sign in
-
-
💻 Strengthening Problem-Solving Skills with LeetCode (Java) Recently explored a few interesting problems that focused on string manipulation, array traversal, and text formatting — each reinforcing clarity and precision in algorithmic thinking: 🔹 Text Justification Implemented a custom text alignment algorithm that evenly distributes spaces between words to fit a given line width. Approach: Greedy + StringBuilder Time Complexity: O(n) 🔹 Two Sum II – Input Array Is Sorted Solved using a two-pointer technique to efficiently find pairs that add up to a target value in a sorted array. Approach: Two Pointers Time Complexity: O(n) 🔹 Is Subsequence Checked whether one string is a subsequence of another using linear traversal and pointer comparison. Approach: Two Pointers Time Complexity: O(n) 🔹 Valid Palindrome Validated alphanumeric palindromes by filtering characters and comparing from both ends. Approach: String cleaning + two-pointer comparison Time Complexity: O(n) These problems helped sharpen my logic-building process and improved my confidence in designing efficient, readable solutions. #LeetCode #Java #ProblemSolving #DSA #Algorithms #Coding #SoftwareEngineering
To view or add a comment, sign in
-
💻 Enhancing Problem-Solving Skills with LeetCode (Java) Recently solved a couple of fundamental algorithmic problems that helped strengthen my understanding of two-pointer techniques, array manipulation, and writing efficient solutions. 🔹 Container With Most Water Implemented an optimised two-pointer approach to find the maximum water area between vertical lines. Instead of checking every pair (which would be O(n²)), the solution smartly moves the pointer at the shorter height inward to explore potentially larger areas. Approach: Two Pointers, Greedy Time Complexity: O(n) Space Complexity: O(1) 🔹 3Sum Solved the classic triplet-finding challenge by sorting the array and using two pointers to efficiently search for combinations that sum to zero. Also handled duplicates to avoid repeated triplets. Approach: Sorting + Two Pointers Time Complexity: O(n²) Space Complexity: O(1) (excluding output list) These problems helped sharpen my understanding of pointer movement, edge-case management, and designing clean, efficient solutions. #LeetCode #Java #Algorithms #DSA #Coding #ProblemSolving #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
🌳 Day 65 of #LeetCode Journey 🔹 Problem: 106. Construct Binary Tree from Inorder and Postorder Traversal 🔹 Difficulty: Medium 🔹 Language: Java Today’s problem is about rebuilding a binary tree when you’re given its inorder and postorder traversal arrays. 🧩 Key Idea: The last element in postorder is always the root. In inorder traversal, elements to the left of the root are in the left subtree, and elements to the right are in the right subtree. We recursively build the tree using this property. 💡 Approach: Start from the end of the postorder array to get the root. Use a hashmap to store inorder indices for O(1) lookup. Recursively construct the right subtree first, then the left subtree (since we’re moving backward in postorder). 🧠 Concepts reinforced: Recursion HashMap for index lookup Understanding inorder & postorder relationships 🔥 Another step forward in mastering tree construction problems! #LeetCode #100DaysOfCode #Java #CodingChallenge #DataStructures #BinaryTree #Recursion #ProblemSolving #ProgrammingJourney
To view or add a comment, sign in
-
-
💡 LeetCode 1929 – Concatenation of Array 💡 Today, I solved LeetCode Problem #1929: Concatenation of Array, a simple yet satisfying problem that tests your understanding of array manipulation and indexing in Java. ⚙️📊 🧩 Problem Overview: You’re given an integer array nums. Your task is to create a new array ans such that ans = nums + nums (i.e., concatenate the array with itself). 👉 Example: Input → nums = [1,2,1] Output → [1,2,1,1,2,1] 💡 Approach: 1️⃣ Find the length n of the given array. 2️⃣ Create a new array of size 2 * n. 3️⃣ Loop through nums once — place each element both at index i and index n + i. 4️⃣ Return the resulting array. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the array. ✅ Space Complexity: O(n) — For the concatenated array. ✨ Key Takeaways: Practiced index manipulation and array construction. Reinforced the importance of efficient iteration. A great warm-up problem that strengthens logical thinking and array fundamentals. 🌱 Reflection: Even the simplest problems build the foundation for solving more complex ones. Every bit of consistent practice helps in mastering problem-solving and clean coding habits. 🚀 #LeetCode #1929 #Java #ArrayManipulation #DSA #CodingJourney #CleanCode #ProblemSolving #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
⚡ Reflection & Annotations ARE Opacity Here’s the architectural critique no one in enterprise Java wants to admit: Framework “magic” isn’t power — it’s opacity. // Spring Boot – What’s really happening? @RestController @RequestMapping("/news") public class NewsController { @Autowired private NewsService service; // When? How? What thread? @GetMapping("/{id}") public News getNews(@PathVariable String id) { return service.findById(id); // Blocking? Async? Cached? } } Hidden complexity: 🔍 Component scanning via reflection (classpath crawl on startup) 🧩 Proxy creation (CGLIB/JDK proxies wrapping your beans) ⚙️ Transaction management (thread-local state, connection pools) 🧵 Request handling (Tomcat threads? Netty event loop? Depends on your starter) You think you’re writing code — but you’re actually configuring a dynamic runtime you can’t see. Contrast that with Vert.x: // Vert.x – Explicit, honest vertx.createHttpServer() .requestHandler(req -> { String id = req.getParam("id"); // You KNOW this runs on event loop thread newsService.findById(id) .onItem().transform(News::toJson) .subscribe().with( json -> req.response().end(json), failure -> req.response().setStatusCode(500).end() ); }) .listen(8080); Everything is explicit: ✅ You control the event loop ✅ Async boundaries are visible ✅ No hidden schedulers or thread pools ✅ No reflection, no proxy magic 🧠 The point: Reflection and annotations hide the engine. Reactive-first frameworks like Vert.x reveal it — and that transparency is not verbosity, it’s honesty.
To view or add a comment, sign in
-
🚀 Turning Code into Strategy Just wrapped up a fun exercise in algorithmic thinking: finding the best day to buy and sell for maximum profit using Java! This snippet dives into a classic problem—optimizing transactions based on price fluctuations. 📈 Input: {3, 1, 4, 0, 7, 5} 💡 Output: Maximum Profit: 8 | Buy Day: 1 | Sell Day: 7 It’s a great reminder that behind every smart decision is a smart algorithm. #Java #ProblemSolving #Algorithms #CodingJourney #TechInsights #LinkedInLearning
To view or add a comment, sign in
-
-
🚀 Day 146 / 180 of #180DaysOfCode ✅ Today’s Highlight: Revisited LeetCode 3234 — “Count the Number of Substrings With Dominant Ones.” 🧩 Problem Summary: Given a binary string s, the task is to count how many of its substrings have dominant ones. A substring is considered dominant if: number of 1s ≥ (number of 0s)² This creates an interesting balance check between zeros and ones, pushing you to think about substring ranges, prefix behavior, and efficient counting techniques. 💡 Core Takeaways: Great exercise in string analysis and prefix-based reasoning Highlights how mathematical conditions influence algorithm design Reinforces handling frequency relationships inside a sliding or expanding window Efficient counting becomes essential due to potential O(n²) substrings 💻 Tech Stack: Java ⏱ Runtime: 115 ms (Beats 84.11%) 💾 Memory: 47 MB 🧠 Learnings: Strengthened understanding of substring behavior under unique constraints Refined thinking around optimizing brute-force patterns A good reminder of how theoretical conditions (like squaring zeros) change practical implementation choices 📈 Progress: Today’s problem significantly improved my intuition around constraint-based substring evaluation—valuable for more advanced algorithmic challenges ahead. #LeetCode #Java #Algorithms #SubstringProblems #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #180DaysOfCode #LogicBuilding #LearningEveryday
To view or add a comment, sign in
-
Explore related topics
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