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
30-Day Coding Sprint: Subarrays with K Different Integers
More Relevant Posts
-
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
-
-
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
-
-
Day 28 of 30-day Coding Sprint Today, I shifted from the "Two-Pointer/Sliding Window" into the world of Linear Data Structures, starting with the clever simulation of a Queue using Stacks. 232. Implement Queue using Stacks - The Logic: Stacks are LIFO (Last-In, First-Out), while Queues are FIFO (First-In, First-Out). To turn a stack into a queue, you essentially have to "reverse" the order of elements. - The Strategy: Two Stacks Stack 1 (s1): Used as the "Input" buffer. Every push goes here. Stack 2 (s2): Used as the "Output" buffer. - The Secret Sauce: When you need to pop or peek, and s2 is empty, you transfer everything from s1 to s2. This flips the order, making the oldest element (the one at the bottom of s1) the top element of s2. - Complexity: While a single pop might trigger a O(N) transfer, most pop operations happen in O(1). This is known as Amortized O(1) time complexity. #30DaysOfCode #DSASprint #LeetCode #JavaScript #Stacks #Queues #DataStructures #Consistency
To view or add a comment, sign in
-
-
Ever stared at your own code a month later and wondered, "What was I thinking?!" 😵💫 We've all been there! One of the quickest wins for cleaner, more maintainable code is embracing **meaningful and descriptive variable names**. ✨ Instead of using vague names like `x`, `data`, or `temp`, think about what the variable *represents* in your specific context. This makes your code self-documenting, easier to debug, and a joy for your future self (and your teammates!) to read. Take a look at the difference: ```python # Before (unclear purpose) def calc(x, y): return x * y # After (crystal clear!) def calculate_rectangle_area(length, width): return length * width ``` See how much easier it is to understand the "After" example's intent without any extra comments? That's the power of good naming! What's YOUR favorite clean code practice that changed your development life? Share your wisdom below! 👇 #CleanCode #ProgrammingTips #SoftwareDevelopment #DevTips #CodingBestPractices #CodeQuality #DeveloperLife #TechEd
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
-
🚀 𝗠𝗼𝗱𝗲𝗿𝗻 𝗖++ 𝗙𝗲𝗮𝘁𝘂𝗿𝗲: 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝗱 𝗕𝗶𝗻𝗱𝗶𝗻𝗴𝘀 (C++17) One of the most elegant features introduced in Modern C++ is Structured Bindings. They allow you to unpack values from tuples, structs, arrays, and maps in a clean and expressive way. 💡 𝗧𝗵𝗶𝘀 𝗺𝗮𝗸𝗲𝘀 𝗖++ 𝗰𝗼𝗱𝗲 𝗺𝗼𝗿𝗲 𝗿𝗲𝗮𝗱𝗮𝗯𝗹𝗲 𝗮𝗻𝗱 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝘃𝗲. ❌ 𝗕𝗲𝗳𝗼𝗿𝗲 (Verbose Style) std::pair<std::string, int> person = {"Alice", 30}; std::string name = person.first; int age = person.second; Problems 👇 ❌ Verbose code ❌ Harder to read ❌ Repeated object access ✅ 𝗠𝗼𝗱𝗲𝗿𝗻 𝗖++ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 std::pair<std::string, int> person = {"Alice", 30}; auto [name, age] = person; Benefits 👇 ✔ Cleaner syntax ✔ More readable code ✔ Reduces boilerplate ✔ Improves developer productivity 📦 𝗪𝗼𝗿𝗸𝘀 𝗚𝗿𝗲𝗮𝘁 𝗪𝗶𝘁𝗵 𝗦𝗧𝗟 𝗖𝗼𝗻𝘁𝗮𝗶𝗻𝗲𝗿𝘀 Example with std::map: for (const auto& [key, value] : myMap) { std::cout << key << " -> " << value << "\n"; } ✨ No .first ✨ No .second ✨ Just clean and expressive code. 🏆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Modern C++ is evolving toward expressive, readable, and safer code. 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝗱 𝗕𝗶𝗻𝗱𝗶𝗻𝗴𝘀 are a small feature that make a big difference in daily coding. #CPP #ModernCPP #SoftwareEngineering #CPP17 #Coding #CleanCode — 𝗔𝗕𝗛𝗜𝗦𝗛𝗘𝗞 𝗦𝗜𝗡𝗛𝗔
To view or add a comment, sign in
-
-
Finding the Ultimate Peak in a Tree - Day 210 Today Today I worked on a complex tree problem which is LeetCode 124 Binary Tree Maximum Path Sum. This problem is challenging because the path can start and end at any node in the tree and it does not have to pass through the root. I used a recursive strategy to solve this efficiently. At every node, I calculated the maximum contribution from the left side and the right side. A very important part of the logic was using zero if the sum from a child was negative. This means we only include a branch if it actually adds value to our total sum. If it is negative, we just ignore that branch. At each node, I updated a global variable to keep track of the highest sum found so far. I calculated this by adding the current node value to the sums of both its left and right sides. This allowed me to check paths that curve through the current node. For the recursive step, I returned the current node value plus only the better of the two sides. I did this because a single path cannot split in two different directions as it continues up to a parent node. This problem was a perfect way to practice how recursion can manage local calculations while updating a global maximum result. #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #BinaryTree #Recursion #AlgorithmDesign #ProblemSolving #DataStructures #SoftwareEngineering #CodingJourney #LogicBuilding #TechSkills #WebDevelopment #ProgrammingPractice #CleanCode #DailyProgress #JavaScriptDeveloper #CodingChallenge #TechnicalInterview
To view or add a comment, sign in
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled a fun logical puzzle: how to move all zeroes to the end of an array while maintaining the relative order of the non-zero elements. This challenge, which I've documented in my latest PR (https://lnkd.in/dSXWnSES), really tested my ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 to array manipulation. My solution involved iterating through the array and using a pointer to keep track of the position where the next non-zero element should be placed. This allowed me to effectively "compress" the non-zero elements to the front, implicitly leaving zeroes at the end. During the process, I leaned on dry runs to trace the array's state and visualize the pointer movements. When I hit a snag, the debugger was invaluable for stepping through the logic line by line and understanding exactly where my assumptions were off. A key takeaway for me was the power of in-place modification and how a well-placed pointer can simplify array problems significantly. How do you ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 similar array manipulation challenges? Share your strategies below! 📦 Repo: https://lnkd.in/dSXWnSES #ArrayManipulation #JavaScript #Algorithms #ProblemSolving #CodingChallenge #DataStructures #InPlaceAlgorithms #LogicalReasoning #SoftwareDevelopment #LeetCodeStyle
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