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
Longest Repeating Character Replacement Challenge
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 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
-
-
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
-
-
🚀 LeetCode Problem Solved: Rotate Image (Matrix Rotation) Today I practiced an interesting array/matrix problem: Rotate Image. 📌 Problem: Given an n × n matrix, rotate the image 90° clockwise in-place without using another matrix. Example: Input [ [1,2,3], [4,5,6], [7,8,9] ] Output [ [7,4,1], [8,5,2], [9,6,3] ] 💡 Key Idea: Instead of creating a new matrix, we can solve it in two steps: 1️⃣ Transpose the matrix (swap rows and columns) 2️⃣ Reverse each row This transforms the matrix into a 90° clockwise rotated image efficiently. ⚡ Time Complexity: O(n²) 📦 Space Complexity: O(1) (In-place) 🎯 Practicing problems like this helps strengthen understanding of matrix manipulation and in-place algorithms, which are very common in coding interviews. #LeetCode #DSA #JavaScript #CodingPractice #SoftwareDeveloper #Programming #TechLearning
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 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
-
-
Learned this sorting pattern today. When arranging numbers to form the largest possible number, normal sorting doesn't work. Example: [3, 30, 34, 5, 9] → "9534330" The pattern: [3, 30, 34, 5, 9] .map(String) .sort((a, b) => (b + a) - (a + b)) .join("") How it's different: Regular sort (b - a) compares numeric values This pattern compares concatenations instead For 3 vs 30: "303" vs "330" → "330" wins → 3 comes before 30 Been coding for 2 years, first time using this. Always something new to learn. #javascript #coding
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
-
Day 27 :- Optimizing with Flexibility: Longest Repeating Character Replacement ✅ Today’s DSA session focused on a sophisticated variation of the Sliding Window technique. I tackled the Longest Repeating Character Replacement problem on LeetCode, which is a great exercise in balancing window expansion with a specific constraint. The Technical Highlights: Dynamic Sliding Window: I used two pointers to maintain a window of characters. The right pointer expands the window, while the left pointer shrinks it only when the number of replacements needed exceeds the allowed limit k. The Replacement Logic: The core of the solution lies in the formula (window_size - maxFreq). This represents the number of characters in the current window that are not the most frequent character—and therefore must be replaced to make the entire window uniform. Efficiency: By maintaining a frequency array to track the maxFreq within the current window, the algorithm achieves a linear O(n) time complexity, which is significantly more efficient than a nested-loop approach. It’s a great example of how tracking a single global property (maxFreq) can help you maintain an optimal window without needing to re-scan the entire array! 🚀 A huge thanks to my mentor, Anchal Sharma and Ikshit .. for the incredible support and for helping me stay consistent on this journey. Having that accountability makes all the difference! #DSA #Java #100DaysOfCode #SlidingWindow #TwoPointers #ProblemSolving #Mentorship #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
When Division Is Not Allowed: Thinking in Prefix and Suffix 📊 Solved LeetCode 238 – Product of Array Except Self today. The naive solution would use division, but the constraint pushes you to think differently. The elegant approach: - Build a prefix product array (product of elements to the left) - Build a suffix product pass (product of elements to the right) - Combine them in O(n) time without extra division No nested loops. No division. Linear time. Key takeaway: Many array problems become simple when you think in terms of precomputed cumulative information. 💡 Practical insight: Whenever you see “for each element, compute something excluding itself”, think: - Prefix - Suffix - Two-pass strategy This pattern shows up in range queries, cumulative sums, and DP optimizations. #LeetCode #DSA #Arrays #JavaScript #Algorithms #ProblemSolving #LearnInPublic
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