Day 33 / #100DaysOfCode LeetCode 3013 — Divide an Array Into Subarrays With Minimum Cost II (Hard) Problem (short): Given an array nums, divide it into k subarrays such that: - The first subarray must start at index 0 - The distance between the start of the 2nd and kth subarray is at most dist - The total cost (sum of starting elements of all subarrays) is minimized This is the Hard follow-up of Part I, and the constraints make brute force impossible. Key Challenge: Once k becomes variable, we are no longer choosing just 2 elements. We must dynamically maintain the minimum sum of (k-2) valid starting elements inside a moving window. This is where simple sorting or greedy breaks. Core Idea / Observation: - nums[0] is always included - For each possible ending index, we need: • the smallest (k-2) elements from a sliding window • fast insertion and deletion • fast access to the smallest elements This naturally leads to a two-multiset (two TreeMap) strategy. Approach: 1. Fix nums[0] as the first subarray 2. Use two TreeMaps: • st1: stores the smallest (k-2) elements (contributes to sum) • st2: stores the remaining elements 3. Maintain balance using: • automatic shifting between maps • invariant: st1 always contains exactly (k-2) smallest elements 4. Slide the window while respecting the dist constraint 5. At each step: • compute current cost = nums[0] + sum(st1) + current element • update minimum I did take help from the editorial here — to understand how to maintain the invariant correctly. This problem is more about data-structure discipline than raw logic. Complexity: - Time: O(n log n) - Space: O(k) (due to TreeMaps) #Leetcode #DSA #Java
LeetCode 3013: Divide Array into Subarrays with Min Cost
More Relevant Posts
-
🚀 Day 23 – LeetCode 1208 | Get Equal Substrings Within Budget Today’s problem focused on optimizing substring transformations under a cost constraint. 🧠 Problem Given two strings "s" and "t", each character change has a cost defined by the ASCII difference. Find the maximum length substring that can be converted within a given budget. 🔍 Key Insight Instead of brute force (O(n²)), convert the problem into: → “Longest subarray with sum ≤ k” This immediately maps to the Sliding Window (Two Pointer) technique. ⚙️ Approach • Calculate cost = |s[i] − t[i]| • Expand window → add cost • If budget exceeded → shrink window • Track max length ⏱ Complexity Time: O(n) Space: O(1) 💻 Code (Java) class Solution { public int equalSubstring(String s, String t, int maxCost) { int left = 0, currentCost = 0, maxLen = 0; for (int right = 0; right < s.length(); right++) { currentCost += Math.abs(s.charAt(right) - t.charAt(right)); while (currentCost > maxCost) { currentCost -= Math.abs(s.charAt(left) - t.charAt(left)); left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen; } } 📌 Takeaway Whenever you see: • longest substring • contiguous • sum constraint Think → Sliding Window Pattern recognition > memorizing solutions. #LeetCode #DSA #SlidingWindow #Java #ProblemSolving #CodingInterview #SoftwareEngineering #100DaysOfCode #Developers #TechCareer
To view or add a comment, sign in
-
🔥 Day 85 of #100DaysOfCode Today’s challenge: LeetCode: Sliding Window Maximum 🪟📈 📌 Problem Summary Given an integer array nums and a window size k, return the maximum value in each sliding window of size k. Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output → [3,3,5,5,6,7] 🧠 Approach: Monotonic Deque (Optimal Solution) Instead of recalculating the max for every window (which would be slow), we maintain a deque that stores indices in decreasing order of values. ⚙️ Key Steps: Remove elements from the back of deque → if they are smaller than the current element (because they’ll never be maximum again). Add current index to the deque. Remove front index → if it is outside the current window. The front of deque always contains ✅ the maximum element of the window. 🚀 Why This Works The deque always maintains elements in decreasing order, so the largest element is always at the front. ⏱ Time Complexity: O(n) Each element is added and removed at most once. 💾 Space Complexity: O(k) ⚡ Performance Runtime: 30 ms Better than ~70% submissions. 💡 What I Learned When you need max/min in a sliding window → think Monotonic Queue. Removing useless elements early keeps solution efficient. Advanced data structure knowledge gives huge performance gains. Two Pointers → Sliding Window → Monotonic Queue The progression is real. 🔥 On to Day 86 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Deque #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
#PostLog135 ✅Range Sum Query 2D – Immutable (LeetCode 304) I worked on a problem where we need to find the sum of numbers inside a rectangle in a 2D matrix — and we need to answer many such queries efficiently. If we calculate the sum every time by looping through the rectangle, it will be slow. So instead, Use a smart technique called 2D Prefix Sum. 💡 What to do: 1.First, precompute a prefix sum matrix. 2.This stores cumulative sums so we don’t need to recalculate again and again. 3.After preprocessing, each query can be answered in O(1) time. ⏱ Time Complexity: Preprocessing: O(n × m) Each query: O(1) 🚀 What I Learned: How to extend 1D prefix sum to 2D. How preprocessing can make repeated queries extremely fast. Importance of avoiding double counting in matrix problems. Small optimizations like this make a huge difference in performance. Slowly getting better at identifying patterns in DSA problems 💪 #LeetCode #DSA #Java #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 20/100 — Bit Manipulation & Modular Arithmetic! Today’s Problem: 1680. Concatenation of Consecutive Binary Numbers 🔹 The Goal: Given an integer $n$, concatenate the binary representations of numbers from $1$ to $n$ into a single string and return its decimal value modulo $10^9 + 7$. 🔹 The Insight: At first glance, this looks like a string problem, but building a massive binary string is a recipe for a Memory Limit Exceeded (MLE) error. The trick is to realize that when you "append" a new number $i$ to your current result, you are essentially shifting your current value to the left by the number of bits in $i$ and then adding $i$. 🔹 The Difficulty: The numbers grow exponentially. To keep things under control, we apply the property of modular arithmetic: $$(A + B) \pmod M = ((A \pmod M) + (B \pmod M)) \pmod M$$ The real challenge? Knowing when the "bit length" of your current number increases (e.g., when moving from 3 to 4, you go from 2 bits to 3 bits). ✨ Achievement: Successfully bypassed string manipulation entirely to create a pure mathematical $O(n)$ solution. 🔍 Steps followed: ✔ Bit-Width Tracking: Monitored when $i$ reached a power of 2 to increment the shift amount. ✔ Efficient Shifting: Used (ans << bitLength) | i to concatenate values at the bit level. ✔ Modular Discipline: Applied the modulo at every step to prevent integer overflow. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ Thirteen days in and the "bit-shifting" logic is starting to feel like second nature. Onward! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #BitManipulation #MathAlgorithms #SoftwareEngineer #Optimization
To view or add a comment, sign in
-
-
🔥 Day 83 of #100DaysOfCode Today’s problem: LeetCode: Minimum Size Subarray Sum 🎯 📌 Problem Summary Given: An integer target An array nums Return the minimum length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists → return 0. Example: target = 7 nums = [2,3,1,2,4,3] Output → 2 (because [4,3] = 7) 🧠 Approach: Sliding Window (Two Pointers) This is a classic variable-size sliding window problem. ⚙️ Strategy: Use two pointers: l (left) and r (right) Expand window by moving r Keep adding to total When total >= target: Update result Shrink window from left Subtract from total 🔁 Core Logic: for each r: total += nums[r] while total >= target: update min length total -= nums[l] l++ ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 💡 What I Learned Sliding window is extremely powerful for subarray problems. The key is knowing when to expand and when to shrink. Many medium/hard problems are just variations of this pattern. Today’s runtime: ⚡ 1ms (99% faster) Consistency builds mastery. On to Day 84 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Java #DSA #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Merge Sorted Array (LeetCode : 88) 💻✨ In this problem, we are given two sorted arrays. The task is to create a final sorted array inside nums1 without using extra space. I used Two Pointer Technique here 👇 🔹 i → last valid index of nums1 🔹 j → last index of nums2 🔹 k → last index of nums1 (m + n - 1) We compare from the back because if we compare from the front, the data would be overwritten. 👉 If nums1[i] > nums2[j], then we put the larger value at the back. 👉 Otherwise, we put nums2[j]. 👉 Once any one of the arrays is finished, we copy the remaining elements. Time Complexity of this approach: O(m + n) Space Complexity: O(1) (In-place solution) 🚀 This problem reminded me again — If you think in the right direction, the solution becomes much easier. #LeetCode #androidDeveloper#problemslover#dsapattern#twopointer#dailyChallenge #DSA #Java #TwoPointerTechnique #ProblemSolving #CodingJourney #SoftwareDevelopment #InPlaceAlgorithm #DataStructures #AlgorithmThinking
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 4 Problem: 1582. Special Positions in a Binary Matrix Topic: Array, Matrix 🧠 Approach (Simple Thinking): 🔹 A position is special only if it holds a 1 that is alone in its entire row AND its entire column 🔹 Checking row and column for every cell separately is slow and repetitive 🔹 So we pre-compute rowSum and colSum in one pass before making any decisions 🔹 rowSum[i] == 1 means no other 1 exists in that row 🔹 colSum[j] == 1 means no other 1 exists in that column 🔹 If mat[i][j] == 1 and both sums equal 1 — that's your special position 🔹 Preprocessing once and reusing is the real trick here ⏱️ Time Complexity: Two passes through the full matrix → O(m × n) Every cell is visited exactly twice, nothing more 📦 Space Complexity: Two small arrays for row and column sums → O(m + n) No recursion, no extra grid, just two lightweight arrays doing all the work I wrote a full breakdown with dry run, analogy and step by step code walkthrough here: https://lnkd.in/gFgQxQRP If you approached this differently or have a cleaner way to think about it, drop it in the comments — always curious to see different perspectives 💬 See you in the next problem 👋 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
Day 17/30 – LeetCode streak Today’s problem: Find Kth Bit in Nth Binary String (1545). 'S₁ = "0"', and 'Sₙ = Sₙ₋₁ + "1" + reverse(invert(Sₙ₋₁))'. Length of 'Sₙ' is always '2ⁿ - 1', with a '1' sitting exactly in the middle. The structure looks like this: Sₙ = [Sₙ₋₁] + '1' + reverse(invert(Sₙ₋₁)) So for any position 'k': - Let 'mid = 2^(n-1)' (the middle index, 1-based). - If 'k == mid', answer is '1'. - If 'k < mid', it’s in the left half, which is exactly 'Sₙ₋₁' → recurse: 'findKthBit(n-1, k)'. - If 'k > mid', it’s in 'reverse(invert(Sₙ₋₁))'. Mirror it back into 'Sₙ₋₁' at 'mirror = 2*mid - k' (same as '2ⁿ - k'), recursively get that bit from 'Sₙ₋₁', then flip it. Day 17 takeaway: This is one of those problems where drawing the recursive construction once (left + 1 + reversed/inverted left) makes the “mid / mirror / invert” recursion feel natural—and you never have to actually build the string. #leetcode #dsa #java #recursion #consistency
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
-
-
Day 81 of my LeetCode Journey 🔥 📘 Problem: 108. Convert Sorted Array to Binary Search Tree 🎯 Difficulty: Easy 🌐 Platform: LeetCode 🔹 Problem Statement: Given an integer array nums sorted in ascending order, convert it into a height-balanced Binary Search Tree (BST). 🔹 Approach Used: Pick the middle element of the array as the root Recursively build the left subtree using the left half Recursively build the right subtree using the right half This ensures the tree remains height-balanced 🔹 Key Concepts: Binary Search Tree property Divide and conquer Recursion Height-balanced tree construction 🔹 Learning: This problem shows how sorted data can be leveraged to build balanced structures efficiently. Choosing the middle element at every step guarantees minimal height and optimal search performance — a classic divide-and-conquer pattern in tree construction. Time Complexity: O(n) Space Complexity: O(log n) (recursion stack) #LeetCode #Day81 #Java #BST #Trees #DSA #ProblemSolving #Recursion #CodingJourney
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