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
30-Day Coding Sprint: Time Needed to Buy Tickets Optimization
More Relevant Posts
-
😂 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 𝗶𝗻 𝘁𝘄𝗼 𝗲𝗿𝗮𝘀, 𝘀𝗮𝗺𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: 𝗼𝘃𝗲𝗿𝗰𝗼𝗺𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗻𝗴 𝘀𝗶𝗺𝗽𝗹𝗲 𝗹𝗼𝗴𝗶𝗰 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 ✅ #Programming #SoftwareEngineering #DeveloperHumor #CleanCode #JavaScript #Coding #ProblemSolving #DeveloperMindset #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Day 14/60 — LeetCode Discipline Problem Solved: Maximum Number of Vowels in a Substring of Given Length (Revision) Difficulty: Medium Today’s practice revisited another elegant application of the sliding window technique. The task was to determine the maximum number of vowels present in any substring of fixed length k. Instead of recalculating the count for every possible substring, the sliding window approach allows the window to move forward while updating the vowel count efficiently. This pattern once again highlights how maintaining a running state can transform a brute-force idea into a clean and optimal solution. 💡 Focus Areas: • Strengthened fixed-size sliding window intuition • Practiced efficient character counting • Improved substring traversal logic • Reinforced constant-time window updates • Focused on writing clean and readable code ⚡ Performance Highlight: Achieved solid runtime efficiency on submission. Each day of deliberate practice adds another layer of clarity to fundamental algorithmic patterns. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #SlidingWindow #Strings #Algorithms #DataStructures #ProblemSolving #CodingJourney #SoftwareEngineering #Programming #Developers #TechCareers
To view or add a comment, sign in
-
-
Day 16 | Round 5 — 30 Days Coding Challenge 🚀 Today I solved the problem “Count Submatrices With Sum Less Than or Equal to K.” 🔹 Problem (Simple Explanation) We are given a 2D grid (matrix) of integers and a value k. Our task is to count how many submatrices starting from the top-left corner (0,0) have a sum less than or equal to k. 💡 Approach / Logic I Used I used the concept of 2D Prefix Sum to efficiently calculate submatrix sums. Steps I followed: 1️⃣ First, I computed the row-wise prefix sum: Each cell stores the sum of elements from the start of the row up to that column. 2️⃣ Then, I converted it into a 2D prefix sum: Each cell now represents the sum of the rectangle from (0,0) to (i,j). 3️⃣ After building the prefix matrix: I traversed every cell. If the value at (i, j) is ≤ k, it means the submatrix from (0,0) to (i,j) satisfies the condition. 4️⃣ Count all such valid submatrices. ⚙ Complexity Time Complexity: O(m × n) Space Complexity: O(m × n) 📌 Key Insight Using prefix sum helps reduce repeated calculations. Instead of recomputing sums for every submatrix, we store cumulative results and reuse them efficiently. ✅ Round 5 — Day 16 Completed This problem strengthened my understanding of 2D prefix sums and matrix-based optimizations. Recognizing when to use prefix sums can significantly improve performance in such problems. #30DaysOfCode #Round5 #Day16 #LeetCode #PrefixSum #2DArray #Matrix #DSA #ProblemSolving #CodingChallenge #CPlusPlus #DeveloperJourney #Consistency #CodeDaily #LearnInPublic #TechGrowth 🚀
To view or add a comment, sign in
-
-
Recently solved LeetCode 225: Implement Stack using Queues, focusing on understanding how to simulate LIFO behavior using FIFO operations. Instead of using two queues, I implemented an optimized single queue approach where: On every push(x), the new element is added to the queue Then the queue is rotated so that the new element moves to the front This ensures that pop() and top() operate in O(1) Key Insight: By reordering elements during insertion, we shift the complexity to push() (O(n)) and keep retrieval operations efficient. Core Logic: Push → Insert + Rotate queue Pop → Remove front Top → Peek front This problem reinforced an important concept: Data structure behavior can be engineered by controlling operation order, not just structure choice. Always interesting to see how constraints (only queue operations allowed) lead to creative design patterns. #leetcode #datastructures #algorithms #coding #softwareengineering #programming #javascript #problemSolving #techlearning #computerscience
To view or add a comment, sign in
-
-
Day 52 on LeetCode — Minimum Recolors to Get K Consecutive Black Blocks 🧩✅ Today’s problem was another clean application of the Sliding Window technique with optimization. 🔹 Approach Used in My Solution The goal was to find the minimum number of recolors (W → B) needed to get k consecutive black blocks. Key idea in the solution: • Treat it as finding a window of size k with minimum 'W' (white blocks) • Count the number of 'W' in the first window of size k • Slide the window across the string: – Remove the left character (if it was 'W') – Add the new right character (if it is 'W') • Keep track of the minimum changes required This avoids recomputation and ensures an efficient linear solution. ⚡ Complexity: • Time Complexity: O(n) • Space Complexity: O(1) 💡 Key Takeaways: • Strengthened understanding of fixed-size sliding window problems • Learned how to convert problems into min/max count in a window • Reinforced optimizing from brute force to O(n) solutions #LeetCode #DSA #Algorithms #DataStructures #SlidingWindow #Strings #TwoPointers #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
Day 48 on LeetCode Minimum Size Subarray Sum 🎯✅ Today’s problem was a perfect application of the Sliding Window technique for optimizing subarray problems. 🔹 Approach Used in My Solution The goal was to find the smallest subarray length whose sum is greater than or equal to the target. Key idea in the solution: • Use two pointers low and high to maintain a dynamic window • Expand the window by moving high and adding elements to currentSum • Once the sum becomes ≥ target, start shrinking the window from the left (low) • Continuously update the minimum length during this process • If no valid subarray is found, return 0 This approach avoids brute force and ensures we process each element at most twice. ⚡ Complexity: • Time Complexity: O(n) • Space Complexity: O(1) 💡 Key Takeaways: • Mastered the Sliding Window technique for variable window size • Learned how to optimize subarray problems from O(n²) to O(n) • Reinforced handling dynamic window expansion and contraction #LeetCode #DSA #Algorithms #DataStructures #SlidingWindow #Arrays #TwoPointers #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
🚀 Day 27/60 — LeetCode Discipline Problem Solved: Length of Last Word Difficulty: Easy Today’s problem looked simple, yet it emphasized a subtle but important skill — handling edge cases cleanly. The goal was to find the length of the last word in a string, ignoring any trailing spaces. Instead of splitting the string or using extra space, the solution efficiently traverses from the end, skipping unnecessary characters and counting only what truly matters. It’s a reminder that strong coding is not always about complexity — sometimes, it’s about precision and clarity in small details. 💡 Focus Areas: • Practiced string traversal from end • Improved handling of trailing spaces • Reinforced clean and efficient logic • Avoided unnecessary extra space usage • Strengthened edge-case thinking ⚡ Performance Highlight: Achieved 0 ms runtime (100% performance). Small problems, when approached with discipline, sharpen the instincts that solve big ones. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #Strings #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #Consistency #TechJourney #LearnToCode
To view or add a comment, sign in
-
-
I've been tackling the inventory system for my #Zeldalike #Godot #Dev project and realized that the things I want to appear in the inventory aren't items you'll find in the world, so making pickups for them didn't make sense! To counter this, I created a custom command line interface. This GIF shows my command line interface (which allows you to /give [item] [quantity]) and the current approach to the Inventory system. All the images in the UI were made by hand, by me (I'm not artist, I just like having visuals for my mockups), which includes the background and panels. It's navigable via D-Pad, WASD, and control stick. There are navigation sound effects, too (of course)! The actual inventory system is straightforward (yet still complex) on the backend, but extremely modular (a top goal of mine for scripts). You can create unique item resources that then populate panels and correspond with 'items to give' in the world. Once I work on an events system, you'll be able to easily configure events to give the player an item using the SAME item resource applied in the UI; there'll be no need to double up on work. #Python #GDScript #Programmer #DevVlog #GameDev
To view or add a comment, sign in
-
-
Today I worked on leetcode problem no. 1415 The k-th Lexicographical Happy String of Length n.” First, let's understand the concept. A happy string is a string that: Uses only the characters 'a', 'b', 'c' Does not allow two adjacent characters to be the same Concepts practiced: Backtracking Lexicographical ordering Recursion Start with an empty string Try adding 'a', 'b', 'c' Skip a character if it is the same as the previous one When the string length becomes n, we found one valid happy string Since we generate them in lexicographical order, the moment we reach the k-th string, that is our answer. #leetcode #leetcode1415 #dsa #datastructures #algorithms #backtracking #recursion #coding #programming #problemSolving #codingpractice #softwareengineering #developer #codinglife #computerscience #codingjourney #learncoding #codingcommunity #buildinpublic #100daysofcode #competitiveprogramming #cpp #techskills
To view or add a comment, sign in
-
-
Abstract Classes vs Interfaces in OOP In object-oriented programming, both abstract classes and interfaces are powerful tools for designing flexible and scalable systems. But when should you use one over the other? 🔹 Abstract Class Can have both abstract and concrete methods Supports fields and constructors Best when you want to share common code among related classes 🔹 Interface Defines only contracts (methods/properties) No implementation details Ideal for enforcing consistency across unrelated classes 👉 Think of an abstract class as a blueprint with partial construction, while an interface is a contract everyone must sign. Choosing wisely between them ensures cleaner architecture, better maintainability, and easier collaboration. #ObjectOrientedProgramming #OOPConcepts #AbstractClass #InterfaceDesign #SoftwareArchitecture #CleanCode #TechTips #ProgrammingInsights #CodeBetter #LinkedInLearning
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