Day 20 of 30-day Coding Sprint Today I tackled 1248. Count Number of Nice Subarrays, which is a brilliant variation of the "Subarray Sum Equals K" problem, translated into parity (odd/even). 1248. Count Number of Nice Subarrays - The Problem: Find the total number of contiguous subarrays that contain exactly k odd numbers. - The Challenge: Unlike fixed-size windows, a "nice" subarray can have any number of even numbers surrounding the k odd ones. If you only count the minimal window, you miss all the valid subarrays formed by trailing/leading even numbers. - The Strategy: Three-Pointer / Temp Counter Logic Use r to expand and l to shrink the window when oddCount === k. The tempCount Trick: When we have exactly k odd numbers, we shrink from the left. Every even number we "skip" from the left still forms a valid "nice" subarray with the current right boundary. By tracking tempCount, we efficiently add up all those variations without re-scanning. - Result: O(N) time complexity and O(1) space—significantly better than the O(N) space required by a Prefix Sum + Hash Map approach. Note: This problem highlights the difference between finding the longest window and counting all windows. The tempCount reset logic (resetting when a new odd number enters from the right) is the key to handling the combinations of even numbers between odd peaks. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #Algorithms #Consistency
1248 Count Number of Nice Subarrays in JavaScript
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 22 of 30-day Coding Sprint Today’s problem, 424. Longest Repeating Character Replacement, is a masterclass in window validation. It’s not just about sliding the window, but knowing exactly when it becomes "invalid." 424. Longest Repeating Character Replacement - The Goal: Find the longest substring containing the same letter after performing at most k replacements. - The Logic: A window is valid if: (Window Length - Frequency of Most Frequent Character) <= k. - This tells us how many characters in the current window aren't the dominant one. If that number is <= k, we can flip them all! - The Strategy: Maintain a frequency hash for the current window. Track maxFreq (the count of the most frequent character in the current window). If the number of "chars to change" exceeds k, shrink the window from the left and recalculate the state. The Efficiency: By using a 26-size array, we keep the character tracking extremely fast O(1) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #ProblemSolving #Consistency
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
-
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
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
-
15 minutes wasted… and it wasn’t even JavaScript’s fault. I was convinced something was wrong with map(). My array looked fine. But this kept printing in my console: [undefined, undefined, undefined] Here’s what I wrote: const doubled = numbers.map((num) => { num * 2; }); Turns out… I forgot one word: 𝗿𝗲𝘁𝘂𝗿𝗻 When you use { } in map(), you need an explicit 𝗿𝗲𝘁𝘂𝗿𝗻. That tiny detail cost me time. Now I always check one thing: Am I returning something or just running code? A small mistake, easy to miss, yet still humbling. What’s a JS bug that made you question your sanity? 👇 #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #JuniorDevelopers #LearnToCode #Programming #CodeDebugging #DeveloperLife #CleanCode
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
-
build a small practice programme: unit convertor Registry Pattern: Instead of massive if/else chains, I used a lookup object (reg) to define unit types and factors. Base Unit Normalization: I converted everything to a "Base Unit" first (e.g., meters), then to the target. This avoids needing a unique formula for every possible pair (like km -> cm). Type Validation: I added a strict check (from.type !== to.type) to prevent incompatible conversions, like trying to convert Weight to Length. Handling Exceptions: Since Temperature requires offsets (like +32) and not just multiplication factors, I separated it into its own switch case logic. #Javascript #WebDev #LearningInPublic #Coding
To view or add a comment, sign in
-
-
Not every problem needs inheritance. Sometimes you just need to add one method. Extension members in C# let you attach new methods, properties, and more to existing types without touching their source code. A string, a List, a third party SDK class. Doesn't matter. public static class StringExtensions { public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value); } Now myString.IsNullOrEmpty() reads like it was always part of the language. Extensions don't break encapsulation, they respect it. You're building on top of the public surface, not reaching into the internals. That's good design. They also shine with interfaces: public static class CollectionExtensions { public static bool IsEmpty<T>(this IEnumerable<T> source) => !source.Any(); } Every class that implements IEnumerable<T> gets this for free. No inheritance. No modification. Clean. C# 14 is pushing this further with proper extension members and cleaner syntax. Composition over inheritance, without sacrificing readability. One thing to keep in mind: extensions are resolved at compile time, not runtime. No polymorphism. Use them for utility and convenience, not core domain logic. #CSharp #DotNet #SoftwareEngineering #OOP #CleanCode #BackendDevelopment #Programming #CSharp14 #SoftwareDevelopment #CodeQuality
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