🚀 3 Ways to Solve Maximum Subarray Sum (Size K) in Java Today I practiced solving a common DSA problem in Java: 👉 Find the maximum sum of a subarray of size K (K = 3) Array: {5, 9, 1, 8, 7} 9+1+8=18 Instead of jumping directly to the optimal solution, I solved it in three different ways to understand the improvement step by step. ✅ 1️⃣ Way 1 – O(n³) (Brute Force) Generate all possible subarrays Check if size equals K Calculate sum ✔ Good for understanding basics ❌ Very slow (3 nested loops) ✅ 2️⃣ Way 2 – O(n²) (Improved) Fix starting index Directly calculate sum of next K elements ✔ Reduced one loop ✔ Better than brute force ✅ 3️⃣ Way 3 – O(n) (Sliding Window) 🔥 Maintain a running window sum Add next element Remove first element when window exceeds size K Update maximum ✔ Most efficient ✔ Interview-friendly ✔ Real-world optimized approach 💡 Key Learning Optimization is not magic. It’s about improving step by step: O(n³) → O(n²) → O(n) Understanding this transition is what truly builds problem-solving skills. I’m continuously improving my Data Structures & Algorithms skills as a Java learner 💻🔥 #Java #DSA #SlidingWindow #ProblemSolving #CodingPractice #JavaDeveloper #LearningJourney
Java Maximum Subarray Sum Size K Problem Solutions
More Relevant Posts
-
Day 23 of problem solving– Valid Anagram | DSA in Java Today I solved the “Valid Anagram” problem. Problem Statement: Given two strings s and t, return true if t is an anagram of s, and false otherwise. 🔹 An anagram means both strings contain the same characters with the same frequency. Approach I Used: Instead of sorting both strings (which takes O(n log n)), I used a frequency array technique for better performance. Logic: If lengths are different → return false. Create an integer array of size 26. Increase count for characters in first string. Decrease count for characters in second string. If all values are zero → it’s a valid anagram. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) (Fixed size array) 📌 Key Learning: Using a frequency counter is more efficient than sorting when dealing with character-based problems. Consistency > Motivation Slowly building problem-solving strength every day. #DSA #Java #100DaysOfCode #CodingJourney #SoftwareEngineer
To view or add a comment, sign in
-
-
🚀 Day 78 of- #100DaysOfCode Today’s problem: Check if the Sentence Is Pangram A pangram is a sentence that contains every letter of the English alphabet at least once. 🔹 Approach I Used: Loop from 'a' to 'z' Check if each character exists in the given string If any character is missing → return false If all characters are present → return true 💻 Java Solution: 🧠 Time Complexity: O(26 * n) → Since we check 26 letters and contains() takes O(n) Simplified: O(n) 📌 Space Complexity: O(1) (No extra data structure used) 💡 What I Learned: Sometimes simple brute-force solutions are clean and efficient enough. Always analyze time complexity even for small loops like 26 characters.
To view or add a comment, sign in
-
-
🚀 Day 23 of My DSA Journey Today I solved “Check if Binary String Has at Most One Segment of Ones” on LeetCode using Java. 🧠 Understanding the Problem The task was to check whether a binary string contains at most one contiguous segment of 1s. A contiguous segment means all the 1s appear together without being separated by 0s. Example: 111000 → ✅ Only one segment of 1s 110011 → ❌ Two separate segments of 1s 💡 Key Observation If a string contains more than one segment of 1s, there must be a pattern where a 0 appears between two groups of 1s, which creates the substring "01" followed later by another 1. So the idea becomes very simple: If the string contains "01" → there are multiple segments of 1s → return false If "01" does not appear → only one segment of 1s exists → return true ⚡ Approach Instead of manually counting segments, I used a string pattern check to detect "01". 📊 Complexity ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 📌 Key Learning Sometimes the best solution comes from recognizing patterns in the data rather than building complex logic. Simplifying the observation can lead to very clean and efficient solutions. On to Day 24 of the journey 🚀 #DSA #Java #LeetCode #CodingJourney #ProblemSolving #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 DAY 69/150 — FINDING PATTERNS THROUGH SORTING! 🚀 Day 69 of my 150 Days DSA Challenge in Java and today I solved a problem that highlights the power of sorting and pattern observation 💻🧠 📌 Problem Solved: Minimum Absolute Difference 📌 LeetCode: #1200 📌 Difficulty: Easy–Medium The task is to find all pairs of elements with the minimum absolute difference in a given array. 🔹 Approach Used Instead of comparing every pair (which would take O(n²)), I used a more optimized approach: • First, sort the array • Then check only adjacent elements • Keep track of the minimum difference • Store all pairs that match this minimum difference Sorting helps reduce unnecessary comparisons and simplifies the logic. ⏱ Complexity Time Complexity: O(n log n) (due to sorting) Space Complexity: O(n) (for storing result pairs) 🧠 What I Learned • Sorting can significantly reduce the complexity of comparison-based problems • Adjacent elements in a sorted array often reveal important patterns • Avoid brute-force when a structured approach exists 💡 Key Takeaway This problem taught me that sometimes the simplest optimization is just reordering the data first. Once sorted, many complex problems become easier to solve. It also strengthened my understanding of how pattern recognition + sorting can lead to efficient solutions. ✅ Day 69 completed 🚀 81 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gYHCJmkv 💡 Sorting is not just a technique — it’s a problem-solving strategy. #DSAChallenge #Java #LeetCode #Sorting #Greedy #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
📌 Optimized Prime Number Check in Java (Time Complexity O(√n)) While practicing problem-solving, I implemented an optimized Prime Number check using mathematical reasoning instead of brute force. Instead of checking divisibility from 2 to n-1 (O(n)), I reduced the complexity to O(√n). 🔍 Key Optimizations Used: 1️⃣ Handle edge cases separately n == 1 → Not prime n == 2 or n == 3 → Prime 2️⃣ Eliminate obvious non-primes early If n % 2 == 0 or n % 3 == 0 → Not prime 3️⃣ Check only up to √n If a number n = a × b, then at least one of a or b must be ≤ √n. This reduces unnecessary computations significantly. ⏱ Complexity Analysis: • Time Complexity → O(√n) • Space Complexity → O(1) 💡 Why This Matters? Optimizing from O(n) to O(√n) shows: Strong mathematical thinking Better algorithm design Interview-level optimization skills Small improvements in complexity can make a huge difference for large inputs. #Java #DataStructures #Algorithms #ProblemSolving #TimeComplexity #CodingInterview #LearningJourney
To view or add a comment, sign in
-
-
🚀 DAY 63/150 — FINDING THE FIRST UNIQUE CHARACTER! 🚀 Day 63 of my 150 Days DSA Challenge in Java and today I solved a problem that focuses on frequency counting and efficient string processing 💻🧠 📌 Problem Solved: First Unique Character in a String 📌 LeetCode: #387 📌 Difficulty: Easy–Medium The task is to find the index of the first non-repeating character in a given string. If every character repeats, the result should return -1. 🔹 Approach Used To solve this efficiently, I used a frequency counting technique. • First, count the frequency of each character in the string • Then iterate through the string again and find the first character whose frequency is 1 This approach avoids unnecessary comparisons and ensures an efficient solution. ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) (since the character set size is fixed) 🧠 What I Learned • Many string problems can be simplified using frequency arrays or hash maps • Breaking the problem into two passes often makes the logic cleaner • Understanding how to track occurrences efficiently helps avoid brute-force solutions 💡 Key Takeaway This problem helped reinforce the idea that choosing the right data structure (like a frequency array or HashMap) can significantly simplify string processing tasks. Even simple problems strengthen the fundamentals that are essential for solving complex interview questions. ✅ Day 63 completed 🚀 87 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gKxiuZEm 💡 Strong fundamentals in strings and hashing build the base for advanced problem-solving. #DSAChallenge #Java #LeetCode #Strings #HashMap #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🚀 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 — 𝗪𝗵𝗶𝗰𝗵 𝗢𝗻𝗲 𝗦𝗵𝗼𝘂𝗹𝗱 𝗪𝗲 𝗨𝘀𝗲? While revising the Java Collection Framework, I realized something important. We often use ArrayList by default. But do we really understand when to use LinkedList instead? Both implement the List interface, but internally they are completely different. 🔹 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 ArrayList is backed by a dynamic array. That means: • Accessing elements using index is very fast • But inserting or deleting in the middle requires shifting elements So it works best when: ✔ We mostly read data ✔ Random access is frequent 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 LinkedList is backed by a doubly linked list. That means: • Insertion and deletion are faster • Accessing elements by index is slower So it works best when: ✔ We frequently add/remove elements ✔ We modify data often 𝗦𝗶𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 ->List<Integer> list1 = new ArrayList<>(); ->List<Integer> list2 = new LinkedList<>(); Same interface. Different internal working. Different performance behavior. 💡 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 Choosing the right data structure is not about syntax. It’s about understanding the use case. The more I revise Collections, the more I realize that fundamentals matter more than memorizing methods. #Java #CollectionFramework #ArrayList #LinkedList #Programming #DSA #LearningJourney
To view or add a comment, sign in
-
-
Refactoring for Clarity: Array Manipulation in Java 👨💻 I’ve just finished a practical exercise on array manipulation. While the goal was simple (summing two arrays), I used it as an opportunity to apply improvements. - Method decomposition: Separated concerns into specialized methods (Read, Calculate, Display). - Input validation: Built a robust loop to handle invalid inputs and prevent crashes. - Data Formatting: Used printf to create a clear, readable results table. Small improvements in logic and organization make a huge difference in software quality. #Java #Algorithms #CleanCode #Backend #LearningToCode
To view or add a comment, sign in
-
-
✨DAY-13: 🔁 Polymorphism in Java – Same Method, Different Behavior! This image perfectly explains one of the most powerful concepts in OOP — Polymorphism 👇 🐾 Base Class: Animal() 🐶 Derived Classes: Dog() and Cat() The programmer simply says: 👉 “Objects, do your thing!” 😎 And what happens? 🐕 Dog responds: “Woof! Woof!” 🐈 Cat responds: “Meow!” Same method call. Different outputs. That’s the beauty of runtime polymorphism (method overriding) in Java. 💡 Technical Insight: When we use a parent class reference like: Animal obj = new Dog(); obj.sound(); Java decides at runtime which method to execute. This is called Dynamic Method Dispatch. 📌 Why Polymorphism Matters: Increases flexibility Improves scalability Promotes clean and maintainable code Follows the “program to interface, not implementation” principle In simple terms: You give the same command… But each object responds in its own way. That’s real-world programming power. 💻🔥 #Java #OOP #Polymorphism #Programming #SoftwareDevelopment #CodingLife #TechConcepts
To view or add a comment, sign in
-
-
🚀 LeetCode Day 18 – Complement of Base 10 Integer Today I solved LeetCode Problem 1009: Complement of Base 10 Integer using Java. 🧠 Problem: Given a non-negative integer n, return the complement of its binary representation. The complement means flipping all bits in the binary form of the number. 📌 Example: Input: n = 5 Binary of 5 → 101 Complement → 010 Output → 2 💡 Approach: • Create a bitmask with all bits set to 1 up to the highest bit of n. • Use the XOR (^) operator with the mask to flip the bits. 💻 Java Code: class Solution { public int bitwiseComplement(int n) { if (n == 0) return 1; int mask = 0, temp = n; while (temp > 0) { mask = (mask << 1) | 1; temp >>= 1; } return n ^ mask; } } ⏱️ Time Complexity: O(log n) 📦 Space Complexity: O(1) 📚 Practicing Data Structures & Algorithms daily to improve problem-solving skills. #LeetCode #Java #DSA #ProblemSolving #CodingJourney #100DaysOfCode
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