Prefix Sum LeetCode Solution in Python

🚀 Solved a LeetCode Problem – Running Sum (Prefix Sum Concept) Today I solved a problem based on the Running Sum / Prefix Sum concept. 🔍 Problem Statement: Given an array, compute a new array where each element at index i represents the sum of all elements from index 0 to i. 💡 My Approach: Instead of recalculating the sum for every index (which would be inefficient), I used an incremental approach: I initialized a result list with the first element. Then, I iterated through the array starting from index 1. At each step, I updated the current element by adding the previous cumulative sum: 👉 Current element = Current value + Previous running sum I stored each updated value in the result list. This way, I reused previously computed results instead of recomputing sums again and again. ⚡ Why this is efficient? Each element is processed only once. No nested loops are used. Avoids redundant calculations. ⏱️ Complexity Analysis: Time Complexity: O(n) → Single pass through the array Space Complexity: O(n) → Extra list used to store results 📌 Key Learning: This problem helped me understand the importance of Prefix Sum technique, which is widely used in problems involving range sums, subarrays, and optimizations. 💻 Code: class Solution: def runningSum(self, nums: List[int]) -> List[int]: res=[] res.append(nums[0]) for i in range(1,len(nums)): nums[i]=nums[i]+nums[i-1] res.append(nums[i]) return res #100DaysOfCode #Python #DSA #CodingJourney #PrefixSum #ProblemSolving

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories