Day 21 of 30-day Coding Sprint Today I solved Binary Subarrays With Sum, using one of the most clever mathematical tricks in the Sliding Window handbook. 930. Binary Subarrays With Sum - The Problem: Find the number of non-empty subarrays with a sum equal to a specific goal. - The Challenge: In a binary array (containing 0s and 1s), multiple windows can satisfy the same sum because zeros don't increase the sum but do create new subarrays. This makes a direct "exactly K" sliding window difficult to implement. - The Strategy: The Difference of "At Most" Instead of calculating "exactly goal" directly, I created a helper function to find subarrays with a sum at most goal. The Formula: Exactly(K) = AtMost(K) - AtMost(K-1) By subtracting the count of subarrays that sum to K-1 from those that sum to K, we are left with exactly the ones that equal K. Result: O(N) time complexity and O(1) space. Note: This "At Most" pattern is a life-saver for subarray problems involving counts. It simplifies the logic significantly—instead of managing complex pointers for a fixed sum, you're just measuring how many windows fit within a limit. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #BinaryArrays #Algorithms #Consistency
Binary Subarrays With Sum: Leveraging At Most Strategy
More Relevant Posts
-
Day 26 of 30-day Coding Sprint 992. Subarrays with K Different Integers - The Problem: Count every single contiguous subarray that contains exactly k different integers. - The Challenge: A standard sliding window is "greedy"; it finds the largest or smallest window that fits a condition. But here, multiple windows of different sizes ending at the same index r could all have exactly k integers. Approach 1: Brute Force - Generating all subarrays and checking unique counts using a HashMap. - Complexity: O(n^2). This will TLE (Time Limit Exceeded) on any competitive platform with a large input. Approach 2: The "Exactly K" via "At Most K" Logic (Optimal) - The Strategy: Just like we did with binary sums on Day 21, we use the formula: Exactly(K) = AtMost(K) - AtMost(K-1) - The Helper: helper(nums, k) counts how many subarrays have at most $k$ distinct elements. - Why it works: Finding "at most" is easy with a sliding window: if map.size > k, we shrink from the left. The number of subarrays ending at r that satisfy "at most k" is simply (r - l + 1). - Complexity: O(n) time and O(k) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #HardProblem #Algorithms #Consistency
To view or add a comment, sign in
-
-
Day 27 of 30-day Coding Sprint 76. Minimum Window Substring - The Goal: Find the smallest substring in s that contains all characters of t (including duplicates). - The Strategy: Expand & Contract - Preprocessing: Build a frequency map (using a 256-size array) for all characters in t. - Expansion (r pointer): Move the right pointer to expand the window. If the current character is part of t and we still need more of it, increment our count. - Contraction (l pointer): Once count == m (meaning the window is "valid"), try to shrink it from the left to find the minimum possible length. - The "Squeeze": As we move l, we update our frequency map. If moving l causes us to lose a required character from t, the window becomes invalid, and we go back to expanding. Result: Efficient O(N + M) time complexity and O(256) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #HardProblem #Algorithms #Consistency
To view or add a comment, sign in
-
-
Day 9 | Round 5 — 30 Days Coding Challenge 🚀 Today I solved the problem “Find K-th Bit in N-th Binary String.” 🔎 Problem (In Simple Words) We are given two numbers n and k. A binary string is built using this rule: S1 = "0" Si = S(i-1) + "1" + reverse(invert(S(i-1))) We need to find the k-th bit in the string Sn. 💡 Understanding the Pattern Each new string is built using three parts: Previous string The character "1" The reversed and inverted version of the previous string Invert means: Change 0 → 1 Change 1 → 0 So every level depends completely on the previous level. 🛠️ Approach I Used Start with base case: S1 = "0" For each level from 2 to n: Invert the previous string Reverse it Concatenate: previous + "1" + reversed inverted string Finally, return the (k-1) index from Sn This directly follows the pattern defined in the problem. ⚙️ Complexity Time Complexity: Exponential string growth (since length doubles each level) Space Complexity: Stores all generated strings This problem helped me understand: Recursive string construction patterns String manipulation (reverse + invert) How problems build on previously generated results Round 5 — Day 9 Completed ✅ Recognizing patterns in construction-based problems makes implementation much clearer. #30DaysOfCode #Round5 #Day9 #StringManipulation #RecursionPattern #DSA #ProblemSolving #LeetCode #CodingChallenge #CPlusPlus #DeveloperJourney #Consistency #CodeDaily #TechGrowth
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: Rotate Image (Matrix Rotation) Today I practiced an interesting array/matrix problem: Rotate Image. 📌 Problem: Given an n × n matrix, rotate the image 90° clockwise in-place without using another matrix. Example: Input [ [1,2,3], [4,5,6], [7,8,9] ] Output [ [7,4,1], [8,5,2], [9,6,3] ] 💡 Key Idea: Instead of creating a new matrix, we can solve it in two steps: 1️⃣ Transpose the matrix (swap rows and columns) 2️⃣ Reverse each row This transforms the matrix into a 90° clockwise rotated image efficiently. ⚡ Time Complexity: O(n²) 📦 Space Complexity: O(1) (In-place) 🎯 Practicing problems like this helps strengthen understanding of matrix manipulation and in-place algorithms, which are very common in coding interviews. #LeetCode #DSA #JavaScript #CodingPractice #SoftwareDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
-
Project Update-VISU CODE Built a Python Code Execution Visualizer that converts Python code into step-by-step execution diagrams to help students better understand programming concepts like loops, functions,oops. 🎥 Demo: https://lnkd.in/g6f2k288 Tech: Python | Flask | HTML | CSS | Mermaid.js #Python #Coding #StudentProject #Programming
update_visucode
https://www.loom.com
To view or add a comment, sign in
-
🚀 March LeetCode Challenge: Day 05/31 | The Power of Parity in the March LeetCode Challenge! One thing I love about competitive programming is finding "The Shortcut." Today, for LeetCode 1758: Minimum Changes To Make Alternating Binary String, I was able to turn a string manipulation problem into a simple mathematical observation. 🧩 The Challenge Given a binary string, what is the minimum number of character flips needed to make it "alternating" (e.g., 0101... or 1010...)? 💡 My Logic: One Loop, Two Results Initially, you might think you need to check the string against two different patterns separately. But there's a more elegant way: The Pattern Rule: In an alternating string starting with 0, the character at index i should be 0 if i is even, and 1 if i is odd. This can be represented simply as i % 2. The Complement: If it takes X operations to make the string start with 0, it will take exactly (Total Length - X) operations to make it start with 1. By calculating one, I automatically knew the other. Taking the min() of these two gave me the optimal answer in a single pass! 📊 Performance Reflection Time Complexity: O(N) – A single traversal of the string. Space Complexity: O(1) – No extra strings created, just a single counter. #LeetCode #CodingChallenge #DynamicProgramming #Cpp #SoftwareEngineering #ProblemSolving #MarchCodingChallenge #VITBhopal #DataStructures #DrGViswanathan #VIT
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
-
🚀 LeetCode Problem Solved: Maximum Number of Vowels in a Substring of Given Length Today I solved LeetCode 1456 – Maximum Number of Vowels in a Substring of Given Length using the Sliding Window Technique. 🔹 Problem Statement: Given a string s and an integer k, find the maximum number of vowels in any substring of length k. 🔹 Approach: Instead of checking every substring separately, I used the Sliding Window algorithm: • Count vowels in the first window of size k • Slide the window forward one character at a time • Add the new character and remove the old one from the count • Track the maximum vowels seen so far This approach optimizes the solution to O(n) time complexity. 📌 Example: Input: s = "abciiidef", k = 3 Output: 3 Explanation: The substring "iii" contains 3 vowels, which is the maximum. 💡 Key Concepts Practiced: ✔ Sliding Window Technique ✔ String Traversal ✔ Efficient Problem Solving Consistent DSA practice on LeetCode is helping me improve my algorithmic thinking and coding efficiency. #LeetCode #DSA #SlidingWindow #ProblemSolving #CodingPractice #Java #LearningInPublic #Programming
To view or add a comment, sign in
-
-
Solved "Subarray Division (Birthday Chocolate)" Problem on HackerRank Today I solved a very interesting beginner-friendly problem that teaches an important concept in programming — Sliding Window / Subarray Logic. 📌 Problem Summary: We are given a list of integers. We need to find how many contiguous segments (subarrays) of length m have a sum equal to d. Example: s = [2,2,1,3,2] d = 4 m = 2 Valid segments: ✔ [2,2] ✔ [1,3] Answer = 2 ways 💡 What I Learned: ✅ How to generate contiguous subarrays ✅ Importance of window size (m) ✅ How to calculate subarray sums efficiently ✅ Why clean logic is better than nested complex loops This problem may look simple, but it builds a strong foundation in: 🔹 Sliding Window Technique 🔹 Array Traversal 🔹 Problem Decomposition 🔹 Time Complexity Thinking 🎯 Why Beginners Must Learn This Concept Many advanced interview problems are based on this same idea: Maximum Subarray Fixed Window Problems Two Pointer Technique Prefix Sum If you understand this clearly, you can solve many medium-level problems easily. Consistency + Strong Basics = Strong Problem Solver 💪 #Python #ProblemSolving #HackerRank #DataStructures #CodingJourney #SlidingWindow #Beginners
To view or add a comment, sign in
-
-
😂 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 𝗶𝗻 𝘁𝘄𝗼 𝗲𝗿𝗮𝘀, 𝘀𝗮𝗺𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: 𝗼𝘃𝗲𝗿𝗰𝗼𝗺𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗻𝗴 𝘀𝗶𝗺𝗽𝗹𝗲 𝗹𝗼𝗴𝗶𝗰 2020: solve a basic odd/even check with a giant chain of if statements 😅 2026: wrap a tiny problem in an unnecessary abstraction / helper call 📦💀 Different style… same issue: using too much for something simple. Real lesson (and it matters) 👇 Good programming is not about writing more code. It’s not about using more libraries either. It’s about: ✅ knowing the simplest correct solution ✅ understanding built-in language features ✅ using libraries when they solve a real problem (not a 1-line one) ✅ keeping code readable, testable, and easy to maintain Libraries are powerful. 🛠️ But engineering judgment is knowing when not to add one. Sometimes the best code is: ◆ smaller ◆ boring ◆ obvious ◆ and done ✅ 💾 Save this for later 🔁 Repost if this is too real 😅 ➕ Follow Rahul Choudhary for more dev humor + practical tips w3schools.com JavaScript Mastery #Programming #SoftwareEngineering #DeveloperHumor #CleanCode #JavaScript #Coding #ProblemSolving #DeveloperMindset #WebDevelopment
To view or add a comment, sign in
-
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