🚀 LeetCode: Subarray Sum The goal is to find a contiguous subarray that adds up to a specific target sum and return its 1-indexed positions. This is a classic problem that tests your ability to manage a dynamic range within an array. 🛠️ My Approach 1. Sliding Window Initialization: I initialized two pointers, s (start) and e (end), both starting at the beginning of the array to represent a dynamic window. 🔡 2. Window Expansion: I used a for loop to move the end pointer e forward, adding each element to a running sum to expand the window. 🧹 3. Dynamic Shrinking: If the current sum exceeded the target, I used a while loop to move the start pointer s forward, subtracting elements from the sum until it was no longer greater than the target. 📍 ❌ If the sum exactly matches the target, we return the 1-indexed positions [s + 1, e + 1] immediately. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(1) #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
LeetCode: Subarray Sum with JavaScript Solution
More Relevant Posts
-
I thought I understood map(), filter() and reduce()… until I wrote their polyfills. We use these methods daily in JavaScript. But I wanted to understand what actually happens behind the scenes. Building polyfills is one of the best ways to master: 1️⃣ Prototypes: How inheritance actually works in JS. 2️⃣ Execution Context: Mastering the behavior of this. 3️⃣ Edge Cases: Handling reduce() accumulators without an initial value. I’ve put together a deep dive into these internals. What’s inside: The logic behind Array.prototype. Step-by-step custom implementations. The "hidden" index logic in .reduce(). Which polyfill was the hardest for you to learn? Let’s discuss below! #Javascript #Chai aur Code #Polyfills
To view or add a comment, sign in
-
When Division Is Not Allowed: Thinking in Prefix and Suffix 📊 Solved LeetCode 238 – Product of Array Except Self today. The naive solution would use division, but the constraint pushes you to think differently. The elegant approach: - Build a prefix product array (product of elements to the left) - Build a suffix product pass (product of elements to the right) - Combine them in O(n) time without extra division No nested loops. No division. Linear time. Key takeaway: Many array problems become simple when you think in terms of precomputed cumulative information. 💡 Practical insight: Whenever you see “for each element, compute something excluding itself”, think: - Prefix - Suffix - Two-pass strategy This pattern shows up in range queries, cumulative sums, and DP optimizations. #LeetCode #DSA #Arrays #JavaScript #Algorithms #ProblemSolving #LearnInPublic
To view or add a comment, sign in
-
I tried implementing the internal working of forEach and map to better understand how they operate under the hood. Both are higher order functions because they accept another function as an argument. Internally, they iterate over the array (typically via a loop) and execute the callback for each element. forEach : Iterates through the array. Executes the provided callback on each element. Does not return a new array (returns undefined). Primarily used for logging map : Iterates through the array. Executes the callback on each element. Stores the callback’s return value in a new array. Returns the new transformed array. Does not mutate the original array. Rewriting these methods manually with a for loop really clarifies their behavioral difference : forEach is about execution, map is about transformation. #JavaScript #WebDevelopment #FunctionalProgramming #LearnInPublic #ChaiAurCode
To view or add a comment, sign in
-
-
Object.freeze() VS Object.seal() 👇 - In freeze, object's structure and values are totally locked. existing properties can't be changed or deleted. new properties can't be added. - In seal, only object's structure is locked. existing properties can be changed but not deleted. new properties can't be added. Important Points 👇 - Both freeze and seal are shallow which means they only affect the outer main object and not the nested objects. - The structure and properties of nested objects can still be changed. - To make seal or freeze deep, we have to apply it recursively on all nested objects through functions or loops. Hitesh Choudhary Piyush Garg Chai Aur Code Akash Kadlag Jay Kadlag #JavaScript #WebDevelopment #FrontendDevelopment #WebDev #Coding #Programming #Developer #LearnJavaScript #LearningInPublic #100DaysOfCode #TechCommunity #SoftwareDevelopment #ObjectOrientedProgramming #ChaiAurCode #ReactJS
To view or add a comment, sign in
-
Throttle is like putting a speed limit on function execution. Resize a window without throttle? Your function fires hundreds of times per second. With throttle? Maximum once every 300ms, no matter how fast you resize. ``` function throttle(fn, delay = 300) { let flag = true; return function(...args) { if (!flag) return; // Still in cooldown fn.apply(this, args); flag = false; setTimeout(() => flag = true, delay); }; } ``` How it works: Execute once, then enter cooldown. All calls during cooldown are ignored. After the delay, function can execute again. Common use cases: 1. Window resize events 2. Scroll events 3. Button clicks (prevent spam) 4. Mouse movement tracking Throttle vs Debounce: 1. Debounce: waits until you stop 2. Throttle: executes at regular intervals while you continue Full implementation with examples: https://lnkd.in/dG7nwKXh Thanks to Akshay Saini 🚀 for the explanation. Where do you use throttling? Let me know if I missed anything - happy to improve it. #JavaScript #WebDev #Coding #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
Day 184: Moving Nodes and Counting Words I am now on Day 184! Today, I practiced more Linked List logic and started working with Strings. Here is what I did today in very simple steps: 1. Rotate List (LeetCode 61) 🔄 I learned how to take the end of a list and move it to the front. How? First, I find the length of the list. Then, I find the right place to "cut" the list and connect the end back to the start. 2. Swap Nodes in Pairs (LeetCode 24) 🤝 I learned how to swap every two nodes. For example, 1 -> 2 -> 3 -> 4 becomes 2 -> 1 -> 4 -> 3. The Trick: I used a "Sentinel" node to keep track of the head. I also tried a Recursive version, which made the code very short and clean! 3. Length of Last Word (LeetCode 58) 📏 I moved to Strings! I had to find the length of the very last word in a sentence. Manual Way: Instead of using easy shortcuts, I started from the end of the string, skipped the empty spaces, and counted the letters until I hit another space. It is a great way to practice loops. My takeaway: Whether it is cutting a list or counting letters backward, logic is all about finding the right starting point! #JavaScript #Coding #Programming #WebDevelopment #DataStructures #Algorithms #SoftwareEngineer #Logic #SimpleLearning #StringManipulation #LinkedList #TechCommunity #DailyCoding #ProblemSolving #CareerGrowth #CodeNewbie
To view or add a comment, sign in
-
Hello Connections! It's long time no see you all. From past some days I'm less active here and doing some self study. Today I was thinking about a randome probelm - You have a wire of "x" meters length. How many circles can be formed using this wire with Equal Radius? In this problem you have only asked for posible circles. I solved it by considering the radius is fixed or the number of circles are fixed. After solving this equation using the formula of Circumference of Circle = 2πr. The equetions I got are :- 1. r = x/(2πn); where n is fixed and the number of circles, 2. n = x/(2πr); where r is fixed and given radius of circles. After getting these equetions, I used my coding knowledge to simulate it. In the video i have shown the working of my code. For any suggestion, please let me know in comments. reposetory link:- https://lnkd.in/d8Pb7RWJ #coding #challenge #math #webdevelopement #javascript #problemsolving
To view or add a comment, sign in
-
Rotate Without Extra Space: Think in Transformations 🔄 Solved LeetCode 48 - Rotate Image today. The elegant trick: 1. Transpose the matrix (swap rows ↔ columns) 2. Reverse each row That’s it. No extra matrix needed. Instead of simulating rotation element by element, the problem becomes a composition of two simple transformations. Key takeaway: Hard matrix problems often reduce to recognizing the right geometric transformation. When you see the pattern, the implementation becomes clean and in-place. Another strong boost to 2D intuition. #LeetCode #DSA #Matrix #InPlaceAlgorithm #JavaScript #ProblemSolving #LearnInPublic
To view or add a comment, sign in
-
LeetCode Problem: Longest Common Prefix What I Learned: • How nested loops simulate 2D comparison (character index vs string index) • Comparing each string character with the first string as a reference • Using the OR operator (||) to handle multiple stopping conditions • Understanding short-circuit evaluation to prevent unnecessary checks • How .slice(0, i) extracts the valid prefix before mismatch • Why return immediately stops the entire function execution • Handling edge cases like complete match or no common prefix • Writing an efficient O(n × m) solution using simple iteration logic Problem Summary: You’re given an array of strings and need to find the longest common prefix among them. The core idea is: Compare each character of the first string With the same position in all other strings. If: • A string becomes shorter • OR characters don’t match → Stop immediately and return the prefix until that index. If no mismatch is found after full iteration → return the entire first string. This problem strengthened my understanding of control flow, string indexing, and early returns in JavaScript. A great example of breaking execution at the right time instead of overcomplicating logic. #100DaysOfLeetCode #leetcode #javascript #problemsolving #codingjourney #DSA #StringManipulation #AlgorithmicThinking Link: https://lnkd.in/gnvmJK-r
To view or add a comment, sign in
-
-
It's 5:45 am & I am still looking at my dreams. Today[2/28/2026] is day 23 of learning javascript Today & tommorow i will learn are: 1. Difference between let, const & var 2. How to use the default parameter 3. Template string, Multiline string, Dynamic string 4. Arrow Function Syntax, params 5. Spread Operator, Array Max, Copy Arrays 6. Object & Array destructuring 7. Keys, Values, Entries, Delete, Seal, Freeze 8. Accessing Object Data: Nested Object, Optional Chaining 9. Looping Object 10. Primitive Type, Non Primitive Type 11. Null Vs Undefines 12. Truthy & Falsy Values 13. ==, === , implicit conversion 14. Block Scope, Global Scope, Simple Unders. of Hoisting 15. Closure 16. Callback Function & pass different function 17. Function Arguments, pass by ref. pass by value 18. Map, ForEach 19. Filter, Find, Reduce #letsconnect #programmer #frontenddeveloper #mernstakedeveloper #Coding
To view or add a comment, sign in
Explore related topics
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