🚀 DSA Practice – Longest Subarray with Sum = K (Positive Numbers) Today I practiced a classic Sliding Window / Two Pointer problem. Problem: Find the longest subarray whose sum equals K, when the array contains only positive numbers. 💡 Key Idea: * Since all numbers are positive, we can use the sliding window technique: Expand the window by moving the right pointer. * If the sum becomes greater than k, shrink the window using the left pointer. Whenever sum == k, update the maximum length. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) Example: arr = [1, 2, 3, 1, 1, 1, 1, 4, 2, 3] k = 3 Longest subarray: [1, 1, 1] Length = 3 This problem is a great example of how understanding constraints (positive numbers) allows us to replace complex approaches like HashMap + Prefix Sum with a simpler and more efficient Sliding Window technique. #DSA #Algorithms #Java #SlidingWindow #LeetCode #SoftwareEngineering
Longest Subarray with Sum K Using Sliding Window
More Relevant Posts
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 33 of Daily DSA 🚀 Solved LeetCode 58: Length of Last Word ✅ Problem: Given a string s, return the length of the last word (a sequence of non-space characters). Approach: First, trim() the string to remove trailing spaces Traverse the string from the end Count characters until a space is encountered 💡 Key Insight: Instead of splitting the string (which uses extra space), we can simply iterate backwards for an efficient solution. ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.17 MB A simple yet important problem to strengthen string traversal techniques. #DSA #LeetCode #Java #Strings #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Day 39 of Daily DSA 🚀 Solved LeetCode 1446: Consecutive Characters ✅ Problem: The power of a string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return its power. Rules: * Substring must be non-empty * Substring must contain only one unique character * Return the maximum such length Approach: Used a simple linear scan to track the current streak of consecutive identical characters and update the maximum. Steps: 1. Initialize max and count both to 1 2. Iterate from index 1 onwards 3. If current character equals previous → increment count 4. Else → reset count to 1 5. Update max at every step 6. Return max ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 29 ms (Beats 2.02%) • Memory: 45.33 MB Sometimes the simplest sliding window — just two variables — is all you need to solve a problem cleanly. #DSA #LeetCode #Java #SlidingWindow #Strings #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 10 Today’s focus: Prefix Sum and Sliding Window techniques. Problems solved: • Binary Subarrays With Sum (LeetCode 930) • Maximum Sum of Distinct Subarrays With Length K (LeetCode 2461) Concepts used: • Prefix Sum with HashMap • Sliding Window technique • Frequency tracking for distinct elements Key takeaway: In Binary Subarrays With Sum, the goal is to count the number of subarrays whose sum equals a given target. This can be solved efficiently using the prefix sum technique combined with a HashMap. As we iterate through the array, we keep track of the running sum and check how many times (currentSum - goal) has appeared before. This allows us to count valid subarrays in O(n) time. In Maximum Sum of Distinct Subarrays With Length K, a fixed-size sliding window is used. While moving the window across the array, we maintain a frequency map to ensure all elements in the window are distinct. If the window contains exactly k unique elements, we update the maximum sum. These problems highlight how recognizing the right pattern—prefix sums for counting subarrays and sliding windows for fixed-length constraints—can significantly reduce brute-force complexity. Continuing to strengthen pattern recognition and consistency in solving DSA problems. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟒 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding the minimum element in a rotated sorted array using binary search. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Minimum in Rotated Sorted Array 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used binary search to reduce the search space • Compared the middle element with the rightmost element Logic: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) • Continued until left meets right 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Rotated arrays require a modified binary search • Comparing with boundary elements helps identify the sorted half • Binary search is not only for exact matches • Reducing the search space is the core idea 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(log n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Binary search is about asking the right question — not just finding the middle. 54 days consistent 🚀 On to Day 55. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge — Day 56 Problem: Find Unique Binary String Given an array nums containing n unique binary strings, each of length n, return any binary string of length n that does not appear in the array. 💡 Solution 1: Diagonal Trick (Optimal) This clever approach comes from Cantor’s diagonal argument. Idea: Construct a new string by looking at the i-th character of the i-th string. Flip the bit (0 → 1, 1 → 0). The new string will differ from every string in nums at least at one position, guaranteeing it’s unique. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 💡 Solution 2: HashSet + Binary Conversion Another approach is: Convert all binary strings to integers and store them in a HashSet. Iterate through possible numbers and find one that is not present in the set. Convert it back to binary and pad with leading zeros if needed. ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(n) The Diagonal Trick is the most efficient and elegant solution. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Day 56/100 | #100DaysOfDSA 🧠⚡ Today’s problem: String Compression A clean in-place array manipulation problem. Core idea: Compress consecutive repeating characters and store the result in the same array. Approach: • Traverse the array using a pointer • Count consecutive occurrences of each character • Write the character to the array • If count > 1 → write its digits one by one • Move forward and repeat Key insight: We don’t need extra space — just carefully manage read & write pointers. Time Complexity: O(n) Space Complexity: O(1) Big takeaway: In-place algorithms require precise pointer control but give optimal space efficiency. Mastering these improves real-world memory optimization skills. 🔥 Day 56 done. #100DaysOfCode #LeetCode #DSA #Algorithms #Strings #TwoPointers #InPlace #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 18 Today’s focus: Sliding Window with uniqueness constraint. Problem solved: • Maximum Erasure Value (LeetCode 1695) Concepts used: • Sliding Window / Two-pointer technique • HashMap for tracking elements • Maintaining running sum Key takeaway: The goal is to find the maximum sum of a subarray with all unique elements. Using a sliding window, we expand the window while elements are unique. If a duplicate is encountered, we shrink the window from the left until the duplicate is removed. A HashMap helps track the presence (or last occurrence) of elements efficiently. At the same time, we maintain a running sum of the current window. Whenever the window is valid (all unique), we update the maximum sum. This approach avoids recalculating subarrays and reduces the complexity to O(n). This problem highlights how combining sliding window + HashMap + running sum can efficiently handle uniqueness constraints. Continuing to strengthen pattern recognition and consistency in solving DSA problems. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
Day 82/100 – LeetCode Challenge ✅ Problem: #43 Multiply Strings Difficulty: Medium Language: Java Approach: Manual Multiplication with Result Array Time Complexity: O(n × m) Space Complexity: O(n + m) Key Insight: Multiply digits from right to left (least significant first). Store intermediate results in array where index i + j + 1 holds current digit. Handle carry by adding to previous index. Solution Brief: Edge case: if either number is "0", return "0". Created result array of size n1 + n2 (max possible digits). Nested loops multiply each digit of num1 with each digit of num2. Accumulated results with proper carry handling. Built final string skipping leading zeros. #LeetCode #Day82 #100DaysOfCode #Math #String #Java #Algorithm #CodingChallenge #ProblemSolving #MultiplyStrings #MediumProblem #Multiplication #Array #DSA
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