📘 DSA Journey — Day 22 Today’s focus: Prefix Sum + Fixed Window optimization. Problem solved: • K Radius Subarray Averages (LeetCode 2090) Concepts used: • Prefix Sum • Fixed-size sliding window • Efficient range sum calculation Key takeaway: The goal is to calculate the average of subarrays centered at each index with radius k. A brute-force approach would recompute sums for every index, leading to O(n·k) time. Instead, using prefix sum, we can compute any subarray sum in O(1) time. For each index i, the valid window is: [i - k, i + k] If this window is within bounds, we calculate the sum using prefix sum and divide by (2k + 1). If not enough elements exist on either side, we return -1. This approach reduces the complexity to O(n) and avoids repeated calculations. This problem highlights how prefix sum helps in efficiently handling range-based queries. Continuing to strengthen fundamentals and consistency in DSA problem solving. #DSA #Java #LeetCode #CodingJourney
Prefix Sum Optimizes LeetCode 2090 Subarray Averages
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
-
-
📘 DSA Journey — Day 29 Today’s focus: Binary Search on answer space. Problem solved: • Find Peak Element (LeetCode 162) Concepts used: • Binary Search • Observing slope / trend • Search space reduction Key takeaway: The goal is to find a peak element (an element greater than its neighbors). Instead of checking all elements, we use binary search by observing the slope: • If nums[mid] < nums[mid + 1] → we are on an increasing slope, so a peak must exist on the right side • Else → we are on a decreasing slope, so a peak lies on the left side (including mid) By following this logic, we eliminate half of the search space each time and find a peak in O(log n) time. The key insight is: A peak is guaranteed to exist, and the direction of slope helps guide the search. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 31 Today’s focus: Binary Search for boundaries and square roots. Problems solved: • Sqrt(x) (LeetCode 69) • Search Insert Position (LeetCode 35) Concepts used: • Binary Search • Search space reduction • Boundary conditions Key takeaway: In Sqrt(x), the goal is to find the integer square root. Using binary search, we search in the range [1, x] and check mid * mid against x to narrow down the answer. This avoids linear iteration and achieves O(log n) time. In Search Insert Position, we use binary search to find either: • The exact position of the target, or • The correct index where it should be inserted The key idea is that when the target is not found, the final position of the left pointer gives the correct insertion index. These problems highlight how binary search is not just for finding elements, but also for determining positions and boundaries efficiently. Continuing to strengthen fundamentals and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 24 Today’s focus: Prefix Sum for range queries. Problem solved: • Count Vowel Strings in Ranges (LeetCode 2559) Concepts used: • Prefix Sum • Efficient range query processing • String boundary checks Key takeaway: The goal is to count how many strings in a given range start and end with a vowel. A direct approach would check each query range individually, leading to higher time complexity. Instead, we preprocess using a prefix sum array: • Mark each word as 1 if it starts and ends with a vowel, else 0 • Build a prefix sum over this array For any query [l, r], the answer can be found in O(1) using: prefix[r] - prefix[l - 1] This reduces the overall complexity significantly when handling multiple queries. This problem highlights how prefix sum is extremely useful for repeated range-based queries. Continuing to strengthen fundamentals and consistency in DSA problem solving. #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
-
-
🚀 DSA Every Day – Day 2 📍 Problem: Minimum Distance to Target Element 💡 Platform: LeetCode 🧠 Approach: Brute Force with Bidirectional Traversal 🔍 Problem Summary: Given an array, a target value, and a starting index, find the minimum distance between the start index and any index where the target exists. ⚙️ Approach Explained: Traverse forward (start → end) Traverse backward (start → beginning) For each occurrence of target: Compute distance → |start - i| Maintain the minimum distance 📈 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) 🎯 Key Takeaways: Always think in terms of distance minimization problems Bidirectional traversal ensures complete coverage Can be optimized further using early stopping if needed Tell me your approach in comments ? Would love if people would like to join me in this habit for learning every day. 🔥 Progress: Day 2/ 60 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #SoftwareEngineering #60DaysOfCode
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 33 Today’s focus: Binary Search for next greater element. Problem solved: • Find Smallest Letter Greater Than Target (LeetCode 744) Concepts used: • Binary Search • Upper bound concept • Circular handling Key takeaway: The goal is to find the smallest character strictly greater than a given target in a sorted array. This is a classic upper bound problem: We use binary search to find the first element greater than the target. During search: • If letters[mid] > target, store it as a possible answer and move left • Else move right An important edge case: If no character is greater than the target, we return the first element (circular behavior). Continuing to strengthen binary search patterns and problem-solving consistency. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 47 of Daily DSA 🚀 Solved LeetCode 74: Search a 2D Matrix ✅ Problem: Given a sorted 2D matrix where: • Each row is sorted • First element of each row > last element of previous row Find whether a target exists in the matrix. Approach: Used an optimized staircase search (top-right traversal). Steps: Start from top-right corner If element == target → return true If element > target → move left If element < target → move down Continue until found or out of bounds ⏱ Complexity: • Time: O(n + m) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.84 MB Sometimes choosing the right starting point (top-right) makes the search super efficient 💡 #DSA #LeetCode #Java #Matrix #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 35 Today’s focus: Binary Search with index patterns. Problem solved: • Single Element in a Sorted Array (LeetCode 540) Concepts used: • Binary Search • Index parity (even/odd pattern) • Search space reduction Key takeaway: The array is sorted and every element appears twice except one. A key observation: Before the single element, pairs start at even indices After the single element, this pattern breaks. Using binary search: • If mid is even and nums[mid] == nums[mid + 1], the single element lies on the right side • Else, it lies on the left side (including mid) By leveraging this pattern, we can find the answer in O(log n) time and O(1) space. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 15 of My DSA Journey Today’s problem: Array Rank Transform 💡 Problem Insight: Given an array, replace each element with its rank when the array is sorted. Rank starts from 1 Equal elements → same rank Ranks must be continuous (no gaps) 🧠 Approach: 🔹 Clone and sort the array 🔹 Use a HashMap to assign ranks to unique elements 🔹 Traverse original array and replace values using the map ⚡ Key Learning: 👉 This is a classic example of Coordinate Compression 👉 Helps reduce large values into a smaller ranked range 💻 Code Logic: Sort copy of array Assign rank only if element not already mapped Replace original values using the map 📊 Result: ✅ 43 / 43 test cases passed ⏱ Runtime: 31 ms 📈 Beat: 58.58% 💾 Memory: 74.74 MB (85.14% better than others) 💭 Takeaway: Simple problems can test clean thinking + handling duplicates properly. Hashing + sorting is a powerful combo 🔥 🔥 Consistency Check: Day 15 Complete Building discipline one problem at a time. #DSA #CodingJourney #LeetCode #Java #ProblemSolving #Consistency #100DaysOfCode
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