Day 17 of 30-day Coding Sprint Today I’ve shifted focus to one of the most efficient techniques in a developer's toolkit: The Sliding Window. 3. Longest Substring Without Repeating Characters - The Challenge: Finding the length of the longest substring where every character is unique. A naive O(n^2) approach would be too slow for large strings. - The Strategy: Optimized Sliding Window Used a Frequency Hash Array (represented as a 256-element array) to store the last-seen index of each character. Two pointers, l (left) and r (right), define the current window. - The Optimization: Instead of moving the left pointer l one by one when a duplicate is found, I "jump" 1 directly to hash[s[r]] + 1. This ensures that the window always contains unique characters in the most efficient way possible. Result: A clean O(n) time complexity with a single pass through the string. Note: The sliding window isn't just about moving pointers; it's about maintaining a state (in this case, uniqueness) and shrinking or expanding the boundaries to satisfy that state. Using a hash array to store indices turns an O(n) "shrink" into an O(1) "jump." #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #Optimization #Consistency
Optimizing Sliding Window Technique for Unique Substrings
More Relevant Posts
-
Day 25 of 30-days Coding Sprint Today was about finding Distinct Pairs with Difference K, a problem that forces you to handle duplicates carefully to avoid overcounting. The Goal: Find unique pairs (a, b) such that b - a = k. The keyword here is distinct; if we have multiple [1, 5] pairs, we only count them once. Approach 1: The Hash Map (Frequency Logic) - The Strategy: Count the frequency of every number. - The Check: 1. If k > 0, check if map[element + k] exists. - If k = 0, check if map[element] > 1 (since a number minus itself is 0). Pros: Great for O(N) time, but requires extra space for the map. Approach 2: Two-Pointer (Sorted Space) The Strategy: Sort the array first to use the "Expand/Shrink" logic. The Decision Logic: If diff == k: Found a pair! Increment count and skip duplicates using a while loop to maintain uniqueness. If diff < k: Need a larger difference, so move the right pointer. If diff > k: Difference is too big, move the left pointer. Complexity: O(N log N) for sorting, but O(1) auxiliary space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #TwoPointers #Algorithms #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
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
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
-
-
Control Flow is not just a programming concept — it’s how our logic actually moves inside the code. In this article, I explained If, Else, Else-If, Nested If-Else, and Switch in a simple and relatable way using real-life examples. Understanding control flow is very important because it builds the foundation of decision-making in JavaScript. 👉 Read here: https://lnkd.in/dypvmNKP Big thanks to Hitesh Choudhary , Piyush Garg and Akash Kadlag for making complex JavaScript concepts easy to understand through Chai Aur Code Their teaching style really helps in building strong fundamentals. Would love your feedback on the article 🙌 #JavaScript #ControlFlow #WebDevelopment #ChaiAurCode #LearningInPublic #CodingJourney
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
-
Hello Connections! It's long time no see you all. From past some days I'm less active here and doing some self study. Today I was thinking about a randome probelm - You have a wire of "x" meters length. How many circles can be formed using this wire with Equal Radius? In this problem you have only asked for posible circles. I solved it by considering the radius is fixed or the number of circles are fixed. After solving this equation using the formula of Circumference of Circle = 2πr. The equetions I got are :- 1. r = x/(2πn); where n is fixed and the number of circles, 2. n = x/(2πr); where r is fixed and given radius of circles. After getting these equetions, I used my coding knowledge to simulate it. In the video i have shown the working of my code. For any suggestion, please let me know in comments. reposetory link:- https://lnkd.in/d8Pb7RWJ #coding #challenge #math #webdevelopement #javascript #problemsolving
To view or add a comment, sign in
-
Another Day, Another Level Up! 💻 Today’s live coding session was packed with amazing concepts! I learned how to make my code cleaner, smarter, and more efficient. Here is a quick summary of what I learned today: Classes & Error Handling: Mastered the basics of classes and how to handle errors properly so the app doesn't crash. 🛠️ Promises: Learned how to manage tasks that take time (Asynchronous JS) using Promises. ⏳ Symbols: Explored this unique data type and how it helps in creating private-like properties. 🔑 Iterables with Symbols: Used Symbol.iterator to make objects behave like arrays so we can loop through them! 🔄 Overwriting Functions: Learned how to use Symbols to overwrite or customize default function behaviors in objects. ✍️ Feeling more confident with JavaScript every day. Step by step, I'm getting closer to becoming a better developer! 💪 Hitesh Choudhary, Piyush Garg, Chai Aur Code, Akash Kadlag, Jay Kadlag #JavaScript #WebDevelopment #CodingJourney #LearningEveryDay #MERNStack #Programming
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
-
-
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
-
-
Most developers don’t fully understand arrays. And that’s a problem. Because arrays are everywhere in JavaScript. So I made this: 👉 15+ Array Methods 👉 With practical examples 👉 Explained in the simplest way No theory overload. Just what actually matters. 💡 If you master arrays, your logic automatically improves. Don’t just scroll… Save it and level up your skills. #WebDevelopment #JavaScriptDeveloper #CodingTips #Programmers #TechEducation #SkillDevelopment #CodeDaily #FrontendDev
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