Optimize O(n²) to O(n) with Simple Trick

Most people solve this in O(n²). I almost did too. But today I learned a simple trick that makes it O(n). 🚀 Day 55/365 — DSA Challenge Solved: Find Pivot Index The problem is simple: Find an index where left sum == right sum Example: [1,7,3,6,5,6] → answer = 3 My first thought: For every index → calculate left sum & right sum Works… But too slow ❌ Then I realized something: You don’t need to recalculate everything. You already have the total sum. 💡 Key idea: Right sum = totalSum - leftSum - current So instead of nested loops… You just keep updating leftSum. One pass. Clean logic. Optimal solution. ⏱ O(n) time 📦 O(1) space This problem taught me: Simple problems still test your thinking. Optimization matters. And most importantly… Don’t overcomplicate. Code 👇 https://lnkd.in/dad5sZfu #DSA #LearningInPublic #Java #Coding #LeetCode #Consistency #365Days365DSAProblems

  • text

To view or add a comment, sign in

Explore content categories