LeetCode Practice - 896. Monotonic Array 🔷Logic Behind “Monotonic Array” (Java) ✔An array is called monotonic if it moves in only one direction: 📌Either it never decreases (increasing or equal) 📌Or it never increases (decreasing or equal) ✔So the idea is very simple: 📌Check if the array follows at least one of these directions. 🔍 Step 1 — Use two flags We take two boolean variables: boolean increasing = true; boolean decreasing = true; 🔄 Step 2 — Compare neighboring elements We loop through the array and compare every pair: What does this mean? If nums[i] > nums[i+1] → array is going down, so it cannot be increasing If nums[i] < nums[i+1] → array is going up, so it cannot be decreasing We keep eliminating possibilities. 🧪 Example 1 [1, 2, 2, 3] Comparisons: 1 ≤ 2 → ok for increasing 2 ≤ 2 → ok 2 ≤ 3 → ok No violation for increasing, so: increasing = true decreasing = false ➡ Result = true 🧪 Example 2 [1, 3, 2] Comparisons: 1 < 3 → not decreasing 3 > 2 → not increasing So: increasing = false decreasing = false ➡ Result = false ✅ Final decision ✔return increasing || decreasing; ✔If either increasing or decreasing is still true, the array is monotonic. #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
Monotonic Array Java Solution
More Relevant Posts
-
🚀 Minimum Absolute Difference (Optimized Java Approach) Today I revisited a classic array problem and implemented a clean, optimized solution using sorting and a two-pass strategy. Leetcode Problem link:https://lnkd.in/gWtQD_FX 💡 Key idea: Sort the array first Adjacent elements now give the minimum possible differences Use: Pass 1 → find the minimum absolute difference Pass 2 → collect all pairs with that difference ✅ Why this approach? Easy to reason about Avoids unnecessary condition checks Optimal time complexity ⏱️ Complexity: Time: O(n log n) (sorting dominates) Space: O(1) extra (excluding output) #Java #DataStructures #Algorithms #LeetCode #ProblemSolving #CleanCode #LinkedList #Sorting #OptimizedCode
To view or add a comment, sign in
-
-
🔥Day 91 of #100DaysOfLeetCode Problem: 1653. Minimum Deletions to Make String Balanced Difficulty: Medium Key Insight: A balanced string must have all 'a's before all 'b's. Any 'b' before an 'a' creates a violation. Approach: Preprocess the string using: - prefixB[i]: number of 'b's strictly before index i - suffixA[i]: number of 'a's strictly after index i For every index i, treat it as a split point and compute: deletions = prefixB[i] + suffixA[i] The minimum over all splits is the answer. Time Complexity: O(n) Space Complexity: O(n) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
🚀 𝐉𝐚𝐯𝐚 𝐓𝐞𝐜𝐡 𝐃𝐫𝐨𝐩: 𝐟𝐢𝐧𝐚𝐥 𝐯𝐬 𝐬𝐞𝐚𝐥𝐞𝐝 𝐜𝐥𝐚𝐬𝐬𝐞𝐬 In Java, we’ve used final classes for years to lock down behavior. They’re great when extension would break invariants or introduce bugs. But sealed classes change the game. 𝐟𝐢𝐧𝐚𝐥 answers: 👉 “This class must NOT be extended.” 𝐬𝐞𝐚𝐥𝐞𝐝 answers: 👉 “This class CAN be extended — but only in ways I explicitly allow.” Why this matters in real systems: - You get controlled polymorphism - The compiler knows all valid subtypes - Exhaustive switch becomes safer and cleaner - Your domain model becomes explicit, not implicit 𝐟𝐢𝐧𝐚𝐥 is about restriction. 𝐬𝐞𝐚𝐥𝐞𝐝 is about designing boundaries. If you’re modeling domains, workflows, or state machines, 𝐬𝐞𝐚𝐥𝐞𝐝 classes often express intent better than 𝐟𝐢𝐧𝐚𝐥 ever could. With 𝐬𝐞𝐚𝐥𝐞𝐝, the compiler knows all possible implementations. That means safer refactors, exhaustive switch, and clearer domain boundaries. ☕ Modern Java isn’t about more features — it’s about better constraints. #Java #SoftwareEngineering #CleanCode #DomainModel #Backend #Spring #Kotlin #JVM
To view or add a comment, sign in
-
-
Day25 - LeetCode Journey Solved LeetCode 344: Reverse String in Java ✅ This was a simple problem on the surface, but it perfectly highlights how powerful clean logic can be. The goal was to reverse a string in-place using O(1) extra space, which means no extra arrays and no shortcuts. Just pure two-pointer logic. Using the left and right pointers and swapping characters step by step felt very satisfying. It’s one of those patterns that looks small but appears everywhere in interviews and real-world problems. Mastering this makes many string and array problems much easier later on. What I liked about this problem is how it teaches efficiency. Instead of creating new memory, we directly modify the existing array. That mindset of optimizing space is extremely important in DSA. Key takeaways: • Strong practice of the two-pointer technique • In-place operations with constant extra space • Clean and readable swapping logic • Reinforced fundamentals of string manipulation ✅ Accepted successfully ✅ 0 ms runtime with optimal performance Sometimes the simplest problems build the strongest foundations. Consistency with basics is what makes complex problems feel easier later 💪 #LeetCode #DSA #Java #Strings #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #TwoPointers #Consistency #DailyPractice
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: Two Sum II (Input Array is Sorted) Implemented an optimized solution in Java using the Two Pointer technique. Since the array is already sorted, we can efficiently adjust pointers based on the current sum and find the required pair without using extra space. ✅ Time Complexity: O(n) ✅ Space Complexity: O(1) Source Code : https://lnkd.in/ew2_GMw9 This problem is a great example of how understanding constraints (sorted input) helps in designing efficient solutions. #LeetCode #Java #DSA #TwoPointers #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
DSA journey 🚀 📌 LeetCode #977 – Squares of a Sorted Array 💻 Language: Java 🔹 Approach (Two Pointer Technique): Initialize two pointers at the start and end of the array Compare squares of both ends Place the larger square at the end of the result array Move pointers inward accordingly Continue until all elements are processed This works because the array is already sorted, but negative numbers can produce larger squares 💡 ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(n) Efficient and elegant ✨ Consistency over perfection 💯 #DSA #Java #LeetCode #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
DSA journey 🚀 📌 LeetCode #167 – Two Sum II (Input Array Is Sorted) 💻 Language: Java 🔹 Approach (Two Pointer Technique): Initialize two pointers at the start and end of the sorted array Calculate the sum of both pointers If the sum equals the target → return 1-based indices If the sum is smaller than the target → move the start pointer forward If the sum is greater than the target → move the end pointer backward Efficient use of the sorted property 💡 ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(1) Step-by-step clarity before optimization ✨ Consistency over perfection 💯 #DSA #Java #LeetCode #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
DSA journey 🚀 📌 LeetCode #1464 – Maximum Product of Two Elements in an Array 💻 Language: Java 🔹 Approach: Traverse the array once to find the largest and second largest elements Update both values in a single loop Apply the formula: (max − 1) × (secondMax − 1) ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(1) Small optimizations, big wins 💡 Consistency over perfection 💯 #DSA #Java #LeetCode #ProblemSolving #LearningInPublic #DSAWithedSlash 🚀
To view or add a comment, sign in
-
-
Java☕ — Interface vs Abstract Class finally clicked 💡 For a long time, I used them randomly. If code compiled, I thought it was correct. Then I learned the real difference 👇 📝Interface = what a class CAN do 📝Abstract class = what a class IS #Java_Code interface Flyable { void fly(); } abstract class Bird { abstract void eat(); } A plane can fly — but it’s not a bird. That single thought cleared everything for me. Use interface when: ✅Multiple inheritance needed ✅Behavior matters ✅You’re defining a contract Use abstract class when: ✅You share base state ✅You provide common logic ✅Relationship is strong Understanding this saved me from messy designs. #Java #Interface #AbstractClass #OOP #LearningJava
To view or add a comment, sign in
-
Singleton breaks easily if you ignore concurrency A Singleton may look correct in single-threaded code. Under multiple threads, it can silently break. What actually goes wrong: 🔹 Two threads enter creation logic at the same time 🔹 Multiple instances get created 🔹 Bugs appear only under load, not locally 🔹 The code “looks fine” but isn’t safe Why this happens: 🔹 Object creation is not automatically thread-safe 🔹 Without proper memory visibility, one thread may see a half-constructed object 🔹 These issues are timing-dependent and hard to reproduce. The real learning: Singleton is not about making the constructor private. It’s about safe publication and controlled initialization. If concurrency is part of your system — the design must assume multiple threads from day one. Core Java depth shows up here: simple patterns, complex consequences. #CoreJava #Java #Concurrency #Multithreading #BackendEngineering #SoftwareEngineering
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