𝗗𝗮𝘆 𝟲𝟴/𝟭𝟬𝟬 — 𝗧𝗶𝗺𝗲 𝗡𝗲𝗲𝗱𝗲𝗱 𝘁𝗼 𝗕𝘂𝘆 𝗧𝗶𝗰𝗸𝗲𝘁𝘀 🎟️ Day 68. Sometimes you don't need to simulate. You just need to think. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟮𝟬𝟳𝟯: Time Needed to Buy Tickets (Easy) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: People in a queue buying tickets. Each person needs a certain number of tickets. They buy one at a time and go to the back of the line if they need more. How long until person k finishes buying? 𝗧𝗵𝗲 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: You could simulate the queue. Or you could realize: People before position k contribute min(tickets[i], target) People after position k contribute min(tickets[i], target - 1) Why target - 1 for people after? Because person k finishes before they get another turn. No simulation needed. Just math. 𝗠𝘆 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: One loop. For each person: If before or at position k: add min(tickets[i], tickets[k]) If after position k: add min(tickets[i], tickets[k] - 1) Sum it up. Done. Time: O(n), Space: O(1) 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: The best solutions eliminate unnecessary work. Simulation is O(n × max(tickets)). Math is O(n). 𝗖𝗼𝗱𝗲: https://lnkd.in/gn58Hcf7 𝗗𝗮𝘆 𝟲𝟴/𝟭𝟬𝟬 ✅ 𝟲𝟴 𝗱𝗼𝘄𝗻. 𝟯𝟮 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #Queue #Algorithms #MathematicalThinking #CodingInterview #Programming #Java #Optimization #LogicalThinking
More Relevant Posts
-
𝗗𝗮𝘆 𝟲𝟵/𝟭𝟬𝟬 — 𝗥𝗲𝗺𝗼𝘃𝗲 𝗞 𝗗𝗶𝗴𝗶𝘁𝘀 Day 69. One day from 70. This problem broke my brain. Then it clicked. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟰𝟬𝟮: Remove K Digits (Medium) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Given a number as a string and k, remove k digits to make the smallest possible number. Example: "1432219", k=3 → "1219" Which 3 digits do you remove? And in what order? 𝗧𝗵𝗲 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: Greedy + Monotonic Stack. Remove a digit if the next digit is smaller. Keep the stack increasing. This builds the smallest number left-to-right. Example: "1432219" See '4' then '3'? Remove '4' See '3' then '2'? Remove '3' See '2' then '2'? Keep both Result: "12219" → remove trailing '9' → "1219" 𝗠𝘆 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: StringBuilder as stack. For each digit: While stack top > current digit AND k > 0: pop and decrement k Append current digit After loop, remove remaining k digits from the end. Strip leading zeros. Time: O(n), Space: O(n) 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: This combines greedy thinking with monotonic stack. Two patterns, one solution. Understanding when to be greedy and when to use a stack—that's the skill. 𝗖𝗼𝗱𝗲: https://lnkd.in/gv36YUfj 𝗗𝗮𝘆 𝟲𝟵/𝟭𝟬𝟬 ✅ 𝟲𝟵 𝗱𝗼𝘄𝗻. 𝟯𝟭 𝘁𝗼 𝗴𝗼. 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 = 𝟳𝟬. #100DaysOfCode #LeetCode #MonotonicStack #GreedyAlgorithm #Algorithms #CodingInterview #Programming #Java #MediumLevel #PatternCombination #Day70Tomorrow
To view or add a comment, sign in
-
📌 LeetCode Daily Challenge — Day 27 Problem: 3786. Cyclic Shifts of a Matrix Topic: Array, Matrix, Math, Simulation 📌 Quick Problem Sense: You're given an m × n matrix and an integer k. Every step: even-indexed rows shift left, odd-indexed rows shift right — repeated k times. Return true if the matrix after k steps is identical to the original. The catch? k can be huge — so simulating step by step is a dead end. 🚫 🧠 Approach (Simple Thinking): 🔹 A row of length n always returns to original after n shifts — but it might return sooner! 🔹 The minimum cyclic period of a row = the smallest divisor d of n such that the row is just a block of size d repeated 🔹 Check it: row[j] == row[j % d] for all j — if true, d is the period! 🔹 Direction (left vs right) doesn't affect the period — both complete their cycle in the same number of steps 🔹 The matrix restores to original iff k % period == 0 for every row 🔹 Get all divisors of n once in O(√n), check each row against them — no simulation needed! 🎯 ⏱️ Time Complexity: Divisors of n → O(√n) Per row period check → O(d(n) × n) All rows → O(m × d(n) × n) Blazing fast — no k-step simulation ever needed! 📦 Space Complexity: Just a divisors list → O(√n) Zero extra matrix copies or simulation buffers! I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/gbqN_Y7a If you solved it using the KMP failure function to find the string period in O(n), I'd love to see that approach, drop it in the comments 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving
To view or add a comment, sign in
-
-
Day 78: Balancing X and Y (The Grid Grind) ⚖️ Problem 3212: Count Submatrices With Equal Frequency of X and Y Yesterday’s logic was so good I had to run it back. The mission: count all submatrices starting from (0,0) that have at least one 'X' and an equal number of 'X's and 'Y's. The Strategy: • Net Balance Trick: Assigned 'X' as 1 and 'Y' as -1. If the prefix sum of a submatrix is 0, the frequencies are equal. Simple math, big brain energy. 🧠 • 2D Prefix Sums: Used the inclusion-exclusion principle to keep the count updated in a single pass. • The "At Least One X" Check: Maintained a separate prefix matrix just to track if an 'X' had even shown up yet. No 'X', no entry. It might not be the most "optimized" code in the world yet, but it passes the tests and the logic is solid. In a world of complex algorithms, sometimes the O(M⋅N) "it just works" approach is the real MVP. 🚀 #LeetCode #Java #DataStructures #Algorithms #DailyCode
To view or add a comment, sign in
-
-
🚀 Just solved the Contains Duplicate problem with a fresh perspective! Instead of going with the traditional sorting + two pointer approach, I used the property of Set (uniqueness) to achieve an O(n) time complexity solution. 💡 Approach: - Traverse the array once - Use a HashSet to track elements - If an element already exists → duplicate found ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 🔁 On the other hand, the sorting + two pointer approach gives: - Time: O(n log n) - Space: O(1) 👉 So it’s a classic trade-off: - Optimize time → use Set - Optimize space → use Sorting+two pointer Really enjoyed breaking down this problem and comparing approaches — small problems like this build strong intuition for bigger ones 💪 #DataStructures #Algorithms #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 Day 352 – Daily DSA Challenge! 🔥 Problem: 📦 Subarray Product Less Than K Given an array nums and an integer k, return the number of contiguous subarrays where the product of all elements is strictly less than k. 💡 Key Insight — Sliding Window (Two Pointers) Brute force would check all subarrays → O(n²) ❌ Instead, we use a sliding window to maintain a valid product. Core idea: 🧠 How It Works 🔹 Expand the window by moving right 🔹 Multiply current element into prod 🔹 If product ≥ k → shrink window from left 🔹 Once valid, all subarrays ending at right are valid 👉 Count added: right - left + 1 ⚡ Optimized Plan ✅ Initialize: left = 0, prod = 1, count = 0 ✅ For each right: Multiply nums[right] While product ≥ k: divide by nums[left] move left Add (right - left + 1) to count ⚙️ Complexity ✅ Time Complexity: O(n) (each element enters and exits window once) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why does this approach fail if negative numbers are allowed? 2️⃣ How would you modify this for sum < k instead of product? 3️⃣ Can you solve this using log transformation + prefix sum? #DSA #Day352 #LeetCode #SlidingWindow #TwoPointers #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
💭 Today’s lesson: Not every problem needs complex logic. Sometimes, it’s about seeing the pattern clearly. I was solving today’s LeetCode problem: 👉 Check if two strings can be made equal with operations At first glance, it felt like a typical string manipulation problem. But the constraint made it interesting: You can only swap characters at positions with the same parity (even ↔ even, odd ↔ odd). Initially, I started overthinking: ->“Do I need to simulate swaps?” ->“Is this a graph / permutation problem?” But then I paused and asked: 👉 What actually changes after unlimited valid operations? 💡 That’s when the key insight clicked: ->Characters at even indices can only rearrange among even positions ->Characters at odd indices can only rearrange among odd positions So instead of simulating swaps, we just need to check: ✔ Do both strings have the same frequency of characters at even positions? ✔ And the same for odd positions? That reduces the problem to a simple frequency comparison — much cleaner and efficient. Implemented it using two frequency arrays (even & odd), and it worked smoothly ✅ 🔍 Big takeaway: Before jumping into implementation, always ask: 👉 What constraints actually limit or define the problem? Sometimes, the best solution is not more code — but better observation. #DataStructures #Algorithms #LeetCode #ProblemSolving #Java #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
Day 72: Binary Search Squared 🏔️ Problem 3296: Minimum Number of Seconds to Make Mountain Height Zero Today’s problem was a masterclass in optimization. The goal: reduce a mountain's height to zero using workers who take progressively more time for each unit of height they remove. The Strategy: • Binary Search on Answer: Since the time needed is monotonic, I used binary search to find the minimum seconds required to finish the job. • Nested Binary Search: Inside that loop, I ran a second binary search for each worker to calculate the maximum height they could handle within that time limit. • Efficiency: This "Double Binary Search" approach kept the runtime lean even with a massive search space up to 10^16. Solving a "Binary Search inside a Binary Search" problem is a great way to test your grip on time complexity. It’s all about finding that optimal boundary. 🚀 #LeetCode #Java #BinarySearch #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
🔥 Day 350 – Daily DSA Challenge! 🔥 Problem: 🔤 Sort Characters By Frequency Given a string s, sort it in descending order based on character frequency. 💡 Key Insight — Frequency + Sorting We solve this in two steps: 1️⃣ Count frequency of each character 2️⃣ Sort characters based on frequency (descending) 🧠 Frequency Concept Each character contributes: Then we arrange characters in decreasing order of this frequency. ⚡ Algorithm Steps ✅ Count frequencies using HashMap ✅ Store unique characters in a list ✅ Sort list based on frequency (descending) ✅ Build result string by repeating characters ⚙️ Complexity ✅ Time Complexity: O(n log k) (k = unique characters) ✅ Space Complexity: O(n) 🚀 Optimization Idea Instead of sorting, we can use bucket sort (since max frequency ≤ n) → O(n) 💬 Challenge for you 1️⃣ Can you solve this using bucket sort in O(n)? 2️⃣ What if input contains Unicode characters? 3️⃣ How would you return characters sorted by increasing frequency? #DSA #Day350 #LeetCode #HashMap #Sorting #Strings #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
Day 81 - LeetCode Journey 🚀 Solved LeetCode 2: Add Two Numbers (Medium) — a classic linked list problem that beautifully combines arithmetic with pointer manipulation. At first, it looks like simple addition. But the twist is that numbers are stored in reverse order as linked lists, and we must simulate digit-by-digit addition. 💡 Core Idea (Simulation + Carry Handling): Traverse both linked lists simultaneously Add corresponding digits along with carry Create a new node for each digit of the result Move forward until both lists and carry are exhausted A dummy node helps in building the result list smoothly. 🤯 Why it works? Because we mimic the exact process of manual addition, handling carry at each step, ensuring correctness even when lengths differ. ⚡ Key Learning Points: • Converting real-world logic into code (digit addition) • Handling carry efficiently • Traversing two linked lists together • Using dummy node for clean construction • Managing different list lengths gracefully • Achieving O(max(n, m)) time and O(1) extra space This problem strengthens both logical thinking and linked list handling. Also, this pattern connects with: Add Binary Multiply Strings Linked List arithmetic problems Big integer calculations ✅ Better understanding of simulation problems ✅ Stronger pointer + arithmetic combination ✅ Improved handling of edge cases (carry, unequal lengths) From simple addition to linked list manipulation — this is where logic meets implementation 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
LeetCode Daily Challenge – Matrix Similarity After Cyclic Shifts Today I solved an interesting problem that involves matrix traversal + cyclic shifts logic. Problem Insight: We are given a matrix and an integer k. Even-indexed rows → shift left Odd-indexed rows → shift right We need to check if the matrix remains similar after k cyclic shifts. Key Idea: Instead of actually shifting the rows (which is costly), we calculate the expected index directly using modulo arithmetic. Why? Because shifting k times is equivalent to shifting k % n times (where n = number of columns). Logic Breakdown: For each element mat[i][j]: If row is even (i % 2 == 0) ➝ Left shift → new index = (j + k) % n If row is odd (i % 2 != 0) ➝ Right shift → new index = (j - k + n) % n Then simply compare: If all elements match expected positions → return true Otherwise → return false Why this approach? Avoids extra space No actual shifting needed Efficient → O(m × n) time complexity What I learned: Modulo is powerful for cyclic problems Always try to avoid simulation when math can solve it Pattern-based thinking helps in matrices Would love to hear if you solved it differently! #LeetCode #DataStructures #Java #CodingJourney #100DaysOfCode #ProblemSolving
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