Prefix Sum Optimizes LeetCode 2090 Subarray Averages

📘 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

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories