Day 23/30 – LeetCode streak Problem: Find All Possible Stable Binary Arrays I A binary array of length 'zero + one' is stable if it uses exactly 'zero' zeros and 'one' ones, and no run of identical bits is longer than 'limit'. Core idea DP state: * 'dp[z][o][0]' = ways to build a stable array with 'z' zeros and 'o' ones, ending in '0'. * 'dp[z][o][1]' = ways to build a stable array with 'z' zeros and 'o' ones, ending in '1'. * To end in '0' at '(z, o)', you must come from some '(z − k, o, 1)' and append a run of 'k' zeros, where '1 ≤ k ≤ limit' and 'k ≤ z'. * Similarly, to end in '1' at '(z, o)', come from '(z, o − k, 0)' and append 'k' ones. * These transitions are range sums over previous states. Instead of recomputing the full sum each time, use a sliding window idea so each state is computed in 'O(1)'. Transitions (sliding window view) For 'z ≥ 1' and 'o ≥ 1': * Ending with '0': sum of states where we append up to 'limit' zeros after a sequence ending in '1'. * Ending with '1': sum of states where we append up to 'limit' ones after a sequence ending in '0'. Day 23 takeaway: This problem is a solid example of combining DP on counts of zeros and ones with run-length constraints, and optimizing naive range-sum transitions using a sliding window — a pattern that appears in many sequence-counting DP problems. #leetcode #dsa #java #dynamicprogramming #consistency
LeetCode Day 23: Stable Binary Arrays I
More Relevant Posts
-
Day 63 — LeetCode Progress (Java) Problem: Crawler Log Folder Required: Given a list of folder operations, return the minimum number of operations needed to go back to the main folder. Idea: Track the current depth like a counter — move forward increases depth, move back decreases depth, and staying does nothing. Approach: Initialize a variable to track current depth. Traverse each log: "../" → move up (decrease depth, but not below 0) "./" → stay in the same folder "x/" → move into a subfolder (increase depth) Final depth represents the number of steps needed to return to the main folder. Time Complexity: O(n) Space Complexity: O(1) #LeetCode #DSA #Java #Simulation #Strings #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 26 Problem: 3548. Equal Sum Grid Partition II Topic: Array, Matrix, Prefix Sum, HashSet, Greedy 📌 Quick Problem Sense: You're given an m × n integer grid. Make one straight cut, horizontal or vertical to split it into two non-empty parts with equal sums. The twist? You're allowed to remove at most one border element (right at the cut edge) from either side to balance the sums. Return true if such a partition is possible! 🧠 Approach (Simple Thinking): 🔹 Compute the total sum of the grid upfront 🔹 Scan row by row, maintain a running top sum, derive bottom = total - top 🔹 The imbalance is diff = top - bottom 🔹 A cut is valid if: diff == 0 → already perfectly balanced ✅ diff equals a corner cell of the top section ✅ diff equals the left-border cell of the current bottom row ✅ diff exists in a HashSet of all values seen so far ✅ 🔹 Use a HashSet to track all border values already scanned, O(1) lookup to check if removing one element fixes the imbalance 🔹 For vertical cuts → simply transpose the matrix and reuse the same horizontal cut logic! 🔹 Also try reversed row order to cover cuts scanned from the opposite direction, 4 passes total, all reusing the same function 🔄 ⏱️ Time Complexity: 4 passes through the grid (original, reversed, transposed, transposed+reversed) → O(m × n) Single scan per pass, HashSet lookups in O(1) — clean and efficient! 📦 Space Complexity: HashSet of seen values → O(m × n) worst case Transpose grid → O(m × n) Overall → O(m × n) I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/g2FHaT4S If you solved it by explicitly enumerating only the border cells, or used a different balance-check trick, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving #Programming
To view or add a comment, sign in
-
-
🚀 Day 39 of #100DaysOfCode Solved 80. Remove Duplicates from Sorted Array II on LeetCode 🔢 🧠 Key Insight: The array is already sorted, and we need to ensure that each element appears at most twice, modifying the array in-place. ⚙️ Approach: 🔹Maintain a pointer i representing the position to place the next valid element 🔹Start iterating from index 2 🔹For each element nums[j], compare it with nums[i] 🔹If they are different, place the element at nums[i + 2] and move the pointer forward This ensures that no element appears more than twice while maintaining the sorted order. ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #Arrays #TwoPointers #Java #ProblemSolving #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
💡 Day 41 of LeetCode Problem Solved! 🔧 🌟28. Find the Index of the First Occurrence in a String🌟 Task : • Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. Example 2: Input: haystack = "leetcode", needle = "leeto" Output: -1 Explanation: "leeto" did not occur in "leetcode", so we return -1. #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfChallenge #CodingJourney #KeepGrowing
To view or add a comment, sign in
-
-
💡 Day 42 of LeetCode Problem Solved! 🔧 🌟1876. Substrings of Size Three with Distinct Characters🌟 Task : • A string is good if there are no repeated characters. • Given a string s, return the number of good substrings of length three in s. • Note that if there are multiple occurrences of the same substring, every occurrence should be counted. • A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "xyzzaz" Output: 1 Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz". Example 2: Input: s = "aababcabc" Output: 4 Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". The good substrings are "abc", "bca", "cab", and "abc". #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfChallenge #CodingJourney #KeepGrowing
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 30 Problem: 2840. Make Two Strings Equal by Swapping Topic: String, Hash Table, Math, Parity 📌 Quick Problem Sense: Two strings of length n. You can swap characters at indices i and j only if j - i is even — on either string, any number of times. Can you make both strings identical? 🤔 This is the natural generalization of yesterday's Day problem same core insight, arbitrary length! 🧠 Approach (Simple Thinking): 🔹 j - i even means i and j have the same parity (both even or both odd) 🔹 So even-indexed positions can only swap among themselves — and since ANY two even positions can swap, they're fully freely rearrangeable 🔹 Same story for odd-indexed positions — completely isolated from even ones 🔹 The strings can be made equal if and only if: multiset(s1[even indices]) == multiset(s2[even indices]) ✅ multiset(s1[odd indices]) == multiset(s2[odd indices]) ✅ 🔹 Use a frequency difference array per parity — one pass, O(n) time, O(1) space 🎯 🔹 If all differences cancel to zero → true, otherwise → false ⏱️ Time Complexity: Single pass through both strings → O(n) 📦 Space Complexity: 2 × 26 frequency counters → O(1) 💡 Connection to Day 29: Yesterday's problem (length 4, fixed swaps 0↔2 and 1↔3) is just a special case of today! The insight is identical — parity groups are isolated. Today it scales to any n. Same thinking, bigger input! 🔗 https://lnkd.in/g_ExG2Xd I wrote a full breakdown with dry run, real-life analogy, side-by-side comparison with Day 29, and step-by-step code walkthrough here 👇 https://lnkd.in/gYHZZRrZ If you solved it by extracting even/odd subsequences, sorting them and comparing as strings, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving #Strings
To view or add a comment, sign in
-
-
Day 41 - Find Pivot Index Solved using a prefix sum approach. First computed the total sum of the array, then traversed once while maintaining a running left sum. For each index, the right sum is calculated using total - left - nums[i]. If both sums match, that index is the pivot. Time Complexity: O(n) #Day41 #LeetCode #Java #PrefixSum #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 62 of #100DaysOfCode 🌱 Topic: Trees / Recursion ✅ Problem Solved: LeetCode 112 – Path Sum 🛠 Approach: Used DFS (recursion) to explore all root-to-leaf paths. Base Case: If node is null → return false If leaf node: Check if target == node.val → return result Otherwise: Reduce target → target - node.val Recurse on left and right subtree #100DaysOfCode #Day62 #DSA #Trees #Recursion #DFS #LeetCode #Java #BinaryTree #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Day 20/100: The "Cheat Code" for String Rotations 🔄 I’m back on the grind! Today’s challenge was checking if one string is a rotation of another (e.g., "waterbottle" and "erbottlewat"). The Strategy: Instead of writing complex loops to shift characters, I used the Concatenation Trick: 1️⃣ Check if lengths are equal. 2️⃣ Create a new string by adding the first string to itself (s1 + s1). 3️⃣ Check if the second string exists inside that combined string. It’s a simple, elegant O(n) solution that shows how sometimes "working smarter" with data structures beats "working harder" with loops. 20% of the way there. Let's keep moving! 🚀 #100DaysOfCode #Java #DSA #Strings #ProblemSolving #Unit2 #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 35 of #75DaysOfLeetCode 🚀 LeetCode 1448 — Count Good Nodes in Binary Tree Just solved an interesting tree problem that really strengthens DFS concepts! 🌳 👉 Problem Insight: A node in a binary tree is considered “good” if no node on the path from root to it has a value greater than it. 💡 Approach: Traverse the tree using DFS Keep track of the maximum value seen so far If current node ≥ max_so_far → it's a good node Update max and continue traversal 🧠 This problem is a great example of: ✔️ Tree traversal (DFS) ✔️ Passing state in recursion ✔️ Decision making at each node ⏱ Complexity: Time: O(n) Space: O(h) 💻 Java Code: class Solution { public int goodNodes(TreeNode root) { return dfs(root, root.val); } private int dfs(TreeNode node, int maxSoFar) { if (node == null) return 0; int count = 0; if (node.val >= maxSoFar) { count = 1; maxSoFar = node.val; } count += dfs(node.left, maxSoFar); count += dfs(node.right, maxSoFar); return count; } } 🔥 Key Takeaway: Always think about what information needs to be carried along the recursion path — here, it's the maximum value so far. #LeetCode #DataStructures #BinaryTree #DFS #Java #CodingInterview #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