𝐒𝐭𝐨𝐩 𝐨𝐯𝐞𝐫-𝐜𝐨𝐦𝐩𝐥𝐢𝐜𝐚𝐭𝐢𝐧𝐠 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲 𝐩𝐫𝐨𝐛𝐥𝐞𝐦𝐬! Most developers brute-force these with O(n²). 🐢, but that won't pass a Senior Dev interview. I’m starting a daily series: 𝐓𝐡𝐞 𝐓𝐞𝐜𝐡 𝐓𝐫𝐞𝐤🧗♂️. One LeetCode pattern, one simple story, one optimized solution. 𝐓𝐨𝐝𝐚𝐲'𝐬 𝐓𝐨𝐩𝐢𝐜: 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲 𝐒𝐮𝐦 𝐄𝐪𝐮𝐚𝐥𝐬 𝐊 I used to find Prefix Sums confusing until I visualized them as a mountain hike. Meet 𝐒𝐮𝐦𝐦𝐢𝐭 𝐒𝐚𝐦—he doesn’t measure the trail twice. He just remembers where he’s been. 𝐓𝐡𝐞 𝐋𝐨𝐠𝐢𝐜: Current Elevation - Goal = A Previous Landmark? If yes, you just found your path. 𝐓𝐡𝐞 𝐎(𝐧) 𝐉𝐚𝐯𝐚 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧: public int subarraySum(int[] nums, int k) { int count = 0, sum = 0; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); // Starting at base camp for (int n : nums) { sum += n; // Climbing higher if (map.containsKey(sum - k)) { count += map.get(sum - k); // Found a path! } map.put(sum, map.getOrDefault(sum, 0) + 1); // Mark the map } return count; } #Java #SoftwareEngineering #DataStructures #LeetCode #CodingTips #TechCommunity
Subarray Sum Equals K Java Solution
More Relevant Posts
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 15. 3Sum 🧠 Approach & Smart Solution: This classic medium-level problem is a great test of optimizing loops! A brute-force O(n³) approach would easily hit a Time Limit Exceeded (TLE). Instead, I optimized it to O(n²) using the Sorting + Two-Pointer technique. • Pseudo-code: First, sort the given array. Iterate through the array with an index 'i'. Skip duplicate elements to avoid duplicate triplets. Set two pointers: 'j' right after 'i', and 'k' at the end of the array. While 'j' is less than 'k': Calculate the sum of elements at i, j, and k. If the sum is 0, we found a valid triplet! Add it to the result list, and smoothly skip any duplicate values for both 'j' and 'k'. If the sum is less than 0, increment 'j' to increase the sum. If the sum is greater than 0, decrement 'k' to decrease the sum. By sorting first, we can systematically eliminate duplicate triplets and efficiently navigate towards the target sum without redundant checks! ⏱️ Time Complexity: O(n²) (Sorting takes O(n log n), and the two-pointer search takes O(n²)) 📦 Space Complexity: O(1) (Auxiliary space, excluding the space required for the output list) 📊 Progress Update: • Streak: 6 Days 🔥 • Difficulty: Medium • Pattern: Two Pointers / Sorting 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering the two-pointer technique on sorted arrays is a massive level-up for optimizing complex algorithms! 💡 #LeetCode #DSA #TwoPointers #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Day 65 of #100DaysOfCode Solved 108. Convert Sorted Array to Binary Search Tree on LeetCode 🔗 🧠 Key Insight: To build a height-balanced BST from a sorted array: 👉 Always pick the middle element as root This ensures: Left half → left subtree Right half → right subtree Balanced structure 🔥 ⚙️ Approach (Divide & Conquer): 1️⃣ Choose middle index: 🔹 mid = start + (end - start) / 2 2️⃣ Create root node: 🔹 node = new TreeNode(nums[mid]) 3️⃣ Build left subtree: 🔹 node.left = build(start, mid - 1) 4️⃣ Build right subtree: 🔹 node.right = build(mid + 1, end) 5️⃣ Return root ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(log n) (recursion stack) #100DaysOfCode #LeetCode #DSA #BinaryTree #BST #DivideAndConquer #Recursion #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 77 — Slow & Fast Pointer (Middle of the Linked List) Another day, another clean application of the slow‑fast pointer pattern — this time without cycle detection, just finding the midpoint efficiently. 📌 Problem Solved: - LeetCode 876 – Middle of the Linked List 🧠 Key Learnings: 1️⃣ The Problem Given the head of a singly linked list, return the middle node. If there are two middle nodes (even length), return the second one. 2️⃣ Why Slow‑Fast Pointer Works Here - `slow` moves 1 step at a time. - `fast` moves 2 steps at a time. - When `fast` reaches the end (or `fast.next == null`), `slow` is exactly at the middle. - For even length, `fast` ends at `null` → `slow` points to the second middle node (perfect for this problem’s requirement). 3️⃣ The Code (Simple & Elegant) while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; 4️⃣ Why Not Just Count Then Traverse? - Brute force: count nodes → traverse again → O(n) but two passes. - Slow‑fast pointer achieves the same in one pass with O(1) extra space. 💡 Takeaway: Slow‑fast pointer isn’t only for cycle detection. It’s a versatile tool for: - Finding middle (this problem) - Detecting cycles (LeetCode 141/142) - Finding duplicate numbers (LeetCode 287) - Happy number detection (LeetCode 202) Each problem adds a new dimension to understanding the same pattern. No guilt about past breaks — just showing up, solving, and growing. #DSA #SlowFastPointer #MiddleOfLinkedList #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Day 94: Slanted Ciphertext & Loop Optimization 📟 Problem 2075: Decode the Slanted Ciphertext Today’s solve was a fun callback to the "ZigZag Conversion" problem I've tackled before. The challenge: read a string that was written diagonally across a matrix and then flattened into a single row. The Strategy: • Diagonal Traversal: The key is calculating the step size. In a slanted cipher, the next character in a diagonal is exactly columns + 1 indices away. • Refining the Loop: My first approach worked well, but I realized I could shave off execution time by adding an early exit. • The "Efficiency" Jump: By adding a simple check, if(j % column == column-1) break;—I stopped the inner loop from looking for diagonal neighbors that would logically fall outside the matrix boundaries. The Result: This small logic tweak dropped my runtime from 28ms down to 18ms, jumping from beating 56% to 97.63% of users. It’s a great reminder that even on "easier" problems, there’s always room to optimize. Seeing that performance graph move to the far left is the best kind of motivation. 🚀 #LeetCode #Java #StringManipulation #Algorithm #Optimization #DailyCode
To view or add a comment, sign in
-
-
📅 Date: April 29, 2026 Day 7 of my LeetCode Journey 🚀 ✅ Problem Solved: 17. Letter Combinations of a Phone Number 🧠 Approach & Smart Solution: Stepping into the world of Recursion! To solve this classic combinatorial problem, I implemented a Backtracking algorithm. Instead of using complex nested loops (which would vary depending on the input length), a recursive helper function elegantly handles the generation of all possible letter combinations. • Pseudo-code: Handle the edge case: If the input string is empty, immediately return an empty list. Create an array to map phone digits (2-9) to their corresponding string of letters. Initialize a recursive 'backtrack' function that takes the current built string and the remaining digits. Base Case: If there are no remaining digits, add the currently built string to the final output list. Recursive Step: Take the first digit from the remaining digits and look up its mapped letters. Loop through each mapped letter: Append the letter to the current string and recursively call the 'backtrack' function with the rest of the digits. This approach beautifully simulates a depth-first search through all possible phone key combinations! ⏱️ Time Complexity: O(4^n * n) (Where 'n' is the length of digits. The worst-case digits like 7 and 9 have 4 letters) 📦 Space Complexity: O(n) (For the recursion call stack depth) 📊 Progress Update: • Streak: 7 Days 🔥 • Difficulty: Medium • Pattern: Backtracking / Recursion 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering backtracking is a massive milestone for tackling complex decision-tree problems in backend logic! 💡 #LeetCode #DSA #Backtracking #Java #Recursion #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
LeetCode 41 – First Missing Positive. 🧩 When I first read this problem, I thought it would be messy. But once I found the pattern, it turned out to be surprisingly clean. The problem in simple terms: Find the smallest positive integer missing from an unsorted array. The real challenge: O(n) time and O(1) extra space. No sorting, no hash maps, no extra arrays. At first, that feels impossible. But here's the trick that clicked for me: The answer has to be between 1 and n+1 (where n = length of array). Why? Because in the best case, if the array contains 1,2,3,...,n, then the missing number is n+1. Otherwise, there's a gap somewhere between 1 and n. Once I realized that, the solution became straightforward: Place each number in its correct position (number x should be at index x-1) | After rearranging, scan to find the first spot where the number doesn't match the index + 1 That index + 1 is our answer What I liked about this problem: It teaches you to work within tight constraints. Instead of adding more memory, you use the array itself as your workspace. If you're preparing for coding interviews, this is one of those problems worth understanding deeply, not for memorizing the solution but for learning how to think under constraints. Have you run into a problem that looked impossible but turned out to have a simple pattern? Curious to hear your experience. #LeetCode #CodingInterview #ProblemSolving #Java #Algorithms
To view or add a comment, sign in
-
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Solved “Search Insert Position” using Binary Search on LeetCode! Today I worked on an interesting problem where the goal is to find the index of a target element in a sorted array. If the target is not present, we return the index where it should be inserted to maintain sorted order. 🔍 Approach: Instead of using a linear search (O(n)), I implemented an efficient Binary Search (O(log n)) approach. 💡 Key Learning: One important detail is calculating the middle index safely: mid = low + (high - low) / 2 This avoids potential integer overflow compared to (low + high) / 2 and ensures correct behavior even for large inputs. ⚙️ Logic: If target == arr[mid] → return mid If target > arr[mid] → search right half Else → search left half If not found → return ‘low’ as the correct insert position 📈 Result: Achieved 100% performance on LeetCode 🚀 This problem reinforced my understanding of: ✔ Binary Search fundamentals ✔ Edge case handling ✔ Writing optimized and safe code Looking forward to solving more problems and improving problem-solving skills! #LeetCode #BinarySearch #Java #DataStructures #Coding #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 71 of Consistency — 111 LeetCode Problems Solved! Today felt like a real breakthrough. I solved one of the most asked “Medium” interview problems — Product of Array Except Self (LeetCode 238) — and hit 95%+ runtime performance (2ms) without using division. But more than the result, here’s what actually mattered 👇 🧠 What I Learned Today Instead of brute force or nested loops, I used a Prefix + Postfix synchronization approach: 👉 Build left products (prefix) 👉 Build right products (postfix) 👉 Combine them in one pass This simple shift: ✔ Eliminates division ✔ Keeps time complexity at O(n) ✔ Makes the solution scalable for large data ⚡ Key Insight Most optimization problems aren’t about “doing more” — they’re about restructuring how data flows. Today’s takeaway: Think in passes, not in loops. 📊 My Progress So Far • ✅ 111 Problems Solved • 🔥 71-Day Streak • 📈 Strong focus on Medium-level problems • ⚡ Improving intuition for optimized solutions 💡 Why This Matters (For You Too) If you're preparing for coding interviews or improving problem-solving: Start identifying patterns (prefix sum, hashing, two pointers) Focus on time complexity thinking early Practice consistency > intensity These are the exact skills companies look for. 📸 I’ve also shared my LeetCode snapshot! #LeetCode #DSA #CodingJourney #SoftwareEngineering #ProblemSolving #Java #TechGrowth #Consistency #100DaysOfCode #InterviewPrep
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
Mastered the Prefix Sum? Now see how it evolves! I just dropped Day 2, where we tackle the Sliding Window to find Maximum Sum Subarrays in O(n). Don't miss it! 👇 https://www.garudax.id/posts/deviprasadpati_java-codinglife-algorithms-share-7454385225280802816-Hf0N?utm_source=share&utm_medium=member_ios&rcm=ACoAADON3r4BIe7r-QXY7S1sm1X4rs_Y2Ch6R2U