Day 18 of 30-day Coding Sprint Today's problem is an example of how to apply sliding window logic to non-contiguous selections. 1423. Maximum Points You Can Obtain from Cards - The Problem: You can only take cards from the beginning or the end of the array. Find the maximum total points by taking exactly k cards. - The Intuition: Picking k cards from the ends is equivalent to leaving a contiguous subarray of size (n - k) in the middle. However, the more direct "Sliding Window" approach is to start with all k cards from the left and gradually swap them for cards on the right. - The Strategy: Initial State: Calculate the sum of the first k cards from the left (lsum). The Shift: Iteratively "remove" one card from the left sum and "add" one card from the far right (rsum). The Comparison: At each step, update the maxSum with the current total. Result: Efficient O(k) time complexity with O(1) space. Key Insight: This problem may seem to require recursion or dynamic programming at first glance, but the sliding window reduces it to a simple linear scan. It’s all about visualizing the window as a flexible boundary that can wrap around the edges of the array. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #ProblemSolving #Consistency
Max Points from Cards with Sliding Window Logic
More Relevant Posts
-
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 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 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
To view or add a comment, sign in
-
-
Day 29 of 30-day Coding Sprint Today's problem, Time Needed to Buy Tickets, is a perfect example of how you can move from a "literal" simulation to a "mathematical" observation. Approach 1: Simulation Using a Queue - The Logic: We treat the problem exactly as described. We use a queue to store pairs of [tickets_needed, original_index]. - The Flow: 1. Take the person from the front. 2. Subtract 1 from their ticket count and increment time. 3. If they still need tickets, push them back to the end of the queue. 4. Stop as soon as the person at original_index === k has 0 tickets left. - Pros: Very easy to visualize and "act out" the problem. - Cons: Higher time complexity O(n * max_tickets). Approach 2: The Optimized One-Pass The Logic: Instead of simulating every second, we calculate how many tickets each person actually buys before the person at index k finishes. The Observation: People at or before index k: They can buy at most tickets[k] tickets. People after index k: They can buy at most tickets[k] - 1 tickets (because once person k buys their last ticket, the clock stops immediately). Result: Clean O(N) time and O(1) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #Queues #Simulation #Optimization #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
-
-
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
-
"Who says code can't be art? 🎨💻 I built this particle system that assembles and reassembles based on user input. It’s amazing what you can create with a little bit of logic and a lot of particles. Let me know your thoughts in the comments! #WebDevelopment #Coding #JavaScript #FrontEndDeveloper #SoftwareEngineering #CreativeCoding #HTML5 #UIUX #Programming #Innovation #TechCommunity #Programming #CreativeTech #WebDev #Portfolio #TechArt"
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
-
𝘾# 𝘾𝙤𝙣𝙨𝙩𝙧𝙪𝙘𝙩𝙤𝙧𝙨: 𝙏𝙝𝙚 𝘽𝙞𝙧𝙩𝙝 𝘾𝙚𝙧𝙩𝙞𝙛𝙞𝙘𝙖𝙩𝙚 𝙤𝙛 𝙔𝙤𝙪𝙧 𝙊𝙗𝙟𝙚𝙘𝙩𝙨 In programming, particularly in C#, the concept of constructors is crucial for creating valid objects. A 𝗰𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 is a specialized method that shares its name with the 𝗰𝗹𝗮𝘀𝘀 and is responsible for 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗶𝗻𝗴 the 𝗼𝗯𝗷𝗲𝗰𝘁 at the moment of its creation. It ensures that objects do not exist in a void or broken state, akin to how a car requires both an engine and wheels to function. The Anatomy of "new": Most people think 𝙣𝙚𝙬 𝙋𝙤𝙞𝙣𝙩() is just a magic spell. In reality, the CLR is doing a very specific dance behind the scenes. When you write: 𝙋𝙤𝙞𝙣𝙩 𝙋𝟭; 1. Stack: The CLR allocates 4 bytes (for the reference). 2. Heap: Currently 0 bytes. P1 is just a pointer sitting there, referring to null. When you write: 𝙋𝟭 = 𝙣𝙚𝙬 𝙋𝙤𝙞𝙣𝙩(); 1. Allocate: the required memory on the Heap (e.g., 8 bytes). 2. Initialize: It zeros out the memory, setting default values (X:0, Y:0). 3. Construct: It calls your User-Defined Constructor to apply any custom logic. 4. Assign: Finally, it points that stack reference (𝗣𝟭) to the new object on the heap. Not all objects are born the same way. C# gives us different tools depending on how much control we need: 1. Default Constructor: Automatically provided by C# if no constructor is defined, this parameter-less constructor initializes an object with standard settings. 2. Parameterized Constructor: This allows developers to enforce specific attributes upon object creation, ensuring criteria like mandatory user emails are met before the object can be instantiated. 3. Static Constructor: A unique constructor that initializes class-level data and is executed only once before any instance is created, preparing the class for use. Constructors are essential as they prevent scenarios where uninitialized objects may lead to errors like NullReferenceException. Mastering constructors is not merely about understanding syntax; it embodies the intent of defining what an object should be for its existence, thereby enhancing application reliability. #CSharp #DotNet #SoftwareDevelopment #ProgrammingBasics #CodingSimplified #TechTips #DEPI #OOP
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