🔥 Day 86/100 of Code – Subarrays with K Different Integers: The “At Most” Pattern Strikes Again! Today revisited a powerful counting technique to solve a distinct-value subarray problem efficiently: ✅ Problem 992: Subarrays with K Different Integers Task: Count subarrays with exactly k distinct integers. Approach: "At most K distinct" subtraction method: Helper: atMost(k) = subarrays with ≤ k distinct integers Answer = atMost(k) - atMost(k-1) atMost uses sliding window + HashMap to track frequency of values Expand right, shrink left if distinct count > k, count valid subarrays ending at r Key Insight: Converting “exactly K distinct” into “at most K distinct” avoids complex exact matching logic — a reusable pattern seen in Problems 930 and 1248. Complexity: O(n) time, O(k) space — efficient and clean. When you master a pattern, solving variations becomes systematic! 🔄🧠 #100DaysOfCode #LeetCode #Java #SlidingWindow #HashMap #SubarrayCounting #Algorithm
Subarrays with K Different Integers: At Most Pattern
More Relevant Posts
-
🔥 Day 307 – Daily DSA Challenge! 🔥 Problem: 🧠 Gray Code Given an integer n, return a sequence of 2ⁿ integers representing the n-bit Gray code sequence — where two consecutive values differ by exactly one bit. 💡 Key Insights: 🔹 Gray Code follows a beautiful bit-manipulation pattern. 🔹 The formula to generate the ith Gray code is: 👉 gray(i) = i ^ (i >> 1) 🔹 This guarantees that adjacent numbers differ by only one bit. 🔹 No recursion or backtracking needed — just pure bitwise magic ✨ 🔹 Total sequence length is always 2ⁿ. ⚡ Optimized Plan: ✅ Compute total size as 1 << n ✅ Iterate from 0 to 2ⁿ - 1 ✅ Convert each number to Gray code using XOR and right shift ✅ Store results in a list and return ✅ Time Complexity: O(2ⁿ) ✅ Space Complexity: O(2ⁿ) 💬 Challenge for you: 1️⃣ Why does i ^ (i >> 1) always change only one bit at a time? 2️⃣ Can you generate Gray code using a recursive reflection method? 3️⃣ How would you print the result in binary string format instead of integers? #DSA #Day307 #LeetCode #GrayCode #BitManipulation #Math #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
LeetCode 3010: Divide an Array Into Subarrays With Minimum Cost I — a neat “read the definition carefully” problem I enjoyed this one because it looks like a partitioning problem… but the optimal solution is just a simple scan. Key insight: When you split the array into 3 subarrays, the cost = sum of the first element of each subarray. The first subarray must start at index 0, so nums[0] is always included. You’re free to choose where subarray 2 and 3 start (somewhere in nums[1..]). To minimize cost, you simply pick the two smallest values from nums[1..]. So the answer is: nums[0] + smallest(nums[1..]) + secondSmallest(nums[1..]) Leetcode problem link:https://lnkd.in/gUrES9Td #leetcode #java #datastructures #algorithms #problemsolving
To view or add a comment, sign in
-
-
Day 51/100 – LeetCode Challenge ✅ Problem: #3634 Minimum Removals to Balance Array Difficulty: Medium Language: Java Approach: Sorting + Sliding Window Time Complexity: O(n log n) Space Complexity: O(1) Key Insight: After sorting, valid subarray must satisfy nums[j] ≤ nums[i] × k for all elements. Find longest valid subarray using sliding window, then minimum removals = n - maxLen. Solution Brief: Sorted array to bring comparable values together. Used two pointers: expand j, shrink i when condition fails. Tracked maximum window length where nums[j] ≤ nums[i] × k. Result = total elements - longest valid subarray length. #LeetCode #Day51 #100DaysOfCode #SlidingWindow #Sorting #Java #Algorithm #CodingChallenge #ProblemSolving #MinimumRemovals #MediumProblem #Array #TwoPointers #DSA
To view or add a comment, sign in
-
-
LeetCode POTD #3013 - Divide an Array Into Subarrays With Minimum Cost II (02 February 2026) This one looks messy at first glance, but the trick is how you frame it. The first subarray is forced to start at index 0. So the real decision is where the last subarray starts. Fix the starting index of the last subarray at i. Now the constraint i(k-1) - i1 <= dist forces the remaining k-2 subarrays to start inside the window: [i - dist, i - 1] At that point, the problem becomes clean: From a sliding window of length dist, continuously maintain the smallest k-2 values. To do this efficiently: -> Use two ordered sets -> One keeps the k-2 smallest elements -> The other holds the rest -> Maintain the sum while the window slides Total cost for each i: nums[0] + nums[i] + sum_of_k-2_smallest Minimum across all valid i is the answer. Key takeaway: Hard problems usually aren’t about complex code -> they’re about choosing the right perspective. Time Complexity -> O(n log n) Space Complexity -> O(n) #LeetCode #POTD #HardProblems #DataStructures #SlidingWindow #Java #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 95/100 of Code – Combination Sum: Backtracking with Unlimited Reuse! Today returned to a classic backtracking problem — foundational for combinatorial search: ✅ Problem 39: Combination Sum Task: Find all unique combinations (with repetition allowed) that sum to target. Approach: Recursive backtracking with index control: At each step, decide to include current candidate (if ≤ remaining target) or skip it If included, stay at same index (allow reuse) If target reaches 0, add current combination to result Use pruning to avoid unnecessary recursion Key Insight: By staying at same index when including, we allow unlimited reuse. By moving to next index when skipping, we ensure all combinations are explored without duplicates. Complexity: O(2^target) worst-case time, O(target) recursion depth. A perfect example of how backtracking elegantly handles "choose with repetition" problems — building solutions incrementally! 🧩🔢 #100DaysOfCode #LeetCode #Java #Backtracking #DFS #Combinations #Algorithm
To view or add a comment, sign in
-
-
LeetCode Practice - 944. Delete Columns to Make Sorted 🧠 Problem Idea ✅ You are given n strings, all of the same length. ✅ Imagine them written one below another like a grid. Example: cba daf ghi We check column by column. Column 0 → c d g → sorted ✅ Column 1 → b a h → NOT sorted ❌ Column 2 → a f i → sorted ✅ So we delete column 1 → answer = 1 🛠️ Key Observation ✅ A column is sorted if characters do not decrease from top to bottom. That means: 📌 strs[0][col] <= strs[1][col] <= strs[2][col] <= ... ✅ If any pair breaks this rule, that column must be deleted. 🚀 Algorithm 🔷 Take number of rows n 🔷 Take the n strings 🔷 For each column 🔷 Compare every row with the next row 🔷 If upperRowChar > lowerRowChar, mark it as invalid 🔷 Count how many columns are invalid #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🔥 Day 98/100 of Code – Permutations: In-Place Backtracking with Swapping! Today revisited the classic permutation problem using an elegant in-place swapping approach: ✅ Problem 46: Permutations Task: Generate all permutations of distinct integers. Approach: Recursive swapping with index tracking: Fix elements step-by-step by swapping them into position At level i, swap nums[i] with each nums[j] where j ≥ i Recurse to i+1, then backtrack by swapping back Base case: when i == nums.length, store current array state Key Insight: By swapping in-place, we avoid extra space for temporary lists and naturally generate permutations without duplicate checks (since elements are distinct). Complexity: O(n × n!) time, O(n) recursion depth — optimal for generating all permutations. A clean, memory-efficient backtracking technique — fundamental for combinatorial generation! 🔄🧩 #100DaysOfCode #LeetCode #Java #Backtracking #Permutations #DFS #Algorithm
To view or add a comment, sign in
-
-
Day 16 – LeetCode 1004 | Sliding Window Done Right (O(n) Solution) Day 16 of solving problems consistently. Solved LeetCode 1004 – Max Consecutive Ones III. Problem: Given a binary array, you can flip at most k zeros. Return the maximum number of consecutive 1s possible. Brute force checks every subarray → O(n²) → wasteful. A better approach is Sliding Window + Two Pointers → O(n). Core logic: • Expand window with right pointer • Count zeros • If zeros exceed k → move left pointer • Track max window length This problem is a good reminder that: Constraints usually hint the optimal technique. If you see “subarray + max/min + linear time” → think Sliding Window first. Consistency builds skill. 16 days. No breaks. Code + explanation in the video 👇 #LeetCode #DSA #Algorithms #SlidingWindow #TwoPointers #Java #ProblemSolving #CodingInterview #SoftwareDeveloper #100DaysOfCode #TechJourney
To view or add a comment, sign in
-
𝐃𝐚𝐲 𝟒 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problems pushed me to think more about optimization, pruning, and duplicate handling. ✅ 𝐏𝐫𝐨𝐛𝐥𝐞𝐦𝐬 𝐒𝐨𝐥𝐯𝐞𝐝 📌 4Sum 📌 Remove Duplicates from Sorted Array 🔹 𝟒𝐒𝐮𝐦 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Sorted the array Fixed two indices and used 𝐭𝐰𝐨 𝐩𝐨𝐢𝐧𝐭𝐞𝐫𝐬 for the remaining pair Applied 𝐞𝐚𝐫𝐥𝐲 𝐩𝐫𝐮𝐧𝐢𝐧𝐠 using the minimum and maximum possible sums Carefully skipped duplicates at every level 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: ✅ Pruning reduces unnecessary iterations ✅ Using long avoids integer overflow ✅ Duplicate handling is the hardest (and most important) part 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: ⏱ Time: O(n³) 📦 Space: O(1) (excluding output) 🔹 𝐑𝐞𝐦𝐨𝐯𝐞 𝐃𝐮𝐩𝐥𝐢𝐜𝐚𝐭𝐞𝐬 𝐟𝐫𝐨𝐦 𝐒𝐨𝐫𝐭𝐞𝐝 𝐀𝐫𝐫𝐚𝐲 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Used 𝐭𝐰𝐨 𝐩𝐨𝐢𝐧𝐭𝐞𝐫𝐬 One pointer tracks the last unique element Overwrote duplicates in-place 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: ✅ Sorted arrays enable in-place solutions ✅ Simple logic can be extremely efficient 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: ⏱ Time: O(n) 📦 Space: O(1) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Optimization is not about writing complex code — it’s about 𝐚𝐯𝐨𝐢𝐝𝐢𝐧𝐠 𝐮𝐧𝐧𝐞𝐜𝐞𝐬𝐬𝐚𝐫𝐲 𝐰𝐨𝐫𝐤. On to 𝐃𝐚𝐲 𝟓 🔁🚀 #DSA #Arrays #TwoPointers #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🔥 Day 309 – Daily DSA Challenge! 🔥 Problem: 🔁 Permutations II Given an array nums that may contain duplicate numbers, return all unique permutations in any order. 💡 Key Insights: 🔹 This is a backtracking problem with an extra twist — duplicates. 🔹 Sorting the array upfront is the key to handling duplicates cleanly. 🔹 Use a used[] boolean array to track which elements are already in the current permutation. 🔹 The golden rule to skip duplicates 👇 👉 If the current number is the same as the previous one and the previous one is not used, skip it. 🔹 This ensures we only generate unique permutations. ⚡ Optimized Plan: ✅ Sort the input array ✅ Use backtracking to build permutations ✅ Track used elements with a boolean array ✅ Add permutation to result when its size equals nums.length ✅ Skip duplicates using: if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; ✅ Backtrack after each recursive call ✅ Time Complexity: O(n! × n) (due to copying permutations) ✅ Space Complexity: O(n) (recursion stack + used array) 💬 Challenge for you: 1️⃣ Why does the condition !used[i - 1] matter for avoiding duplicates? 2️⃣ How would this solution change if all numbers were unique? 3️⃣ Can you generate permutations iteratively instead of using recursion? #DSA #Day309 #LeetCode #Permutations #Backtracking #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
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