🚀 Day 416 of #500DaysOfCode Problem: 1513. Number of Substrings With Only 1s Platform: LeetCode – Medium Today’s challenge was a classic binary-string problem that focuses on counting substrings composed only of '1' characters. Sounds simple—but with constraints up to 100,000 characters, brute force is impossible. 🔍 What I Learned The key insight is: Whenever you find a continuous streak of 1s of length k, it contributes: k⋅(k+1)2\frac{k \cdot (k+1)}{2}2k⋅(k+1)substrings made only of 1s. Example: 111 → • "1" (3 times) • "11" (2 times) • "111" (1 time) Total = 6 So instead of checking all substrings, we just: ➡️ Count lengths of 1-streaks ➡️ Use the formula ➡️ Keep sum modulo 1e9+7 🧠 Why This Problem Is Useful Builds intuition for pattern-counting in strings Reinforces how mathematical optimization replaces brute-force loops Helps in understanding frequency-based substring logic 📌 Output Examples Input: "0110111" → Output: 9 Input: "101" → Output: 2 Input: "111111" → Output: 21 💡 Reflection Simple logic + clever math = powerful optimization. This problem reminded me how often the pattern matters more than the individual characters. #500DaysOfCode #Day416 #LeetCode #Java #CodingJourney
"Day 416 of #500DaysOfCode: Counting 1-Substrings with Math"
More Relevant Posts
-
📌 Day 8/100 - Search Insert Position (LeetCode 35) 🔹 Problem: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. 🔹 Approach: I used a binary search approach for efficiency 🔍 1️⃣ Start with two pointers — low and high. 2️⃣ Find the mid index and compare nums[mid] with the target. 3️⃣ If target equals nums[mid], return mid. 4️⃣ If target is smaller, move the high pointer left. 5️⃣ If target is greater, move the low pointer right. 6️⃣ When the loop ends, low gives the correct insert position. 🔹 Key Learning: Binary Search saves time — reducing O(n) to O(log n)! Understanding the condition when to move left/right is key. Even simple problems sharpen logical precision and boundary handling. Each problem strengthens the logic muscle 🧠 — one step closer to mastering algorithms! 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #654 — Maximum Binary Tree 📘 Problem: Given an integer array without duplicates, the task is to build a maximum binary tree. The construction rules are: 1️⃣ The root is the maximum element in the array. 2️⃣ The left subtree is built recursively from elements to the left of the maximum. 3️⃣ The right subtree is built recursively from elements to the right of the maximum. Example: Input → [3,2,1,6,0,5] Output → [6,3,5,null,2,0,null,null,1] 🧠 My Approach: I solved this problem using a recursive divide-and-conquer approach. 1️⃣ Find the index of the maximum element in the given range — this becomes the root. 2️⃣ Recursively build the left subtree from the subarray before the maximum element. 3️⃣ Recursively build the right subtree from the subarray after the maximum element. 💡 What I Learned: ✅ How recursion naturally fits into tree construction problems ✅ The concept of divide and conquer applied to array-based tree building ✅ How to translate problem definitions into direct recursive structure #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🗓 Day 8/ 100 – #100DaysOfLeetCode 📌 Problem 3234: Count the Number of Substrings With Dominant Ones A substring is said to have dominant ones if: 👉 #1s ≥ (#0s)² The task is to count how many substrings in the binary string satisfy this condition. 🧠 My Approach: 🔹 Iterated through substrings while maintaining counts of zeros and ones. 🔹 Used the condition ones ≥ zeros² to determine whether a substring is valid. 🔹 Applied early stopping when the zero count became too large, since the quadratic requirement makes dominance increasingly difficult to achieve. 🔹 This pruning significantly reduced unnecessary checks and improved the overall efficiency. ⏱ Time & Space Complexity Time Complexity: O(n · √n) Because for each starting index, we only explore substrings until the zero count reaches ~√n (beyond which zeros² becomes too large to satisfy). This is a major improvement over the brute-force O(n²). Space Complexity: O(1) Only uses a few counters (ones, zeros, indices). 💡 Key Learning: This problem beautifully shows how mathematical constraints can simplify substring evaluation. Recognizing that zeros affect the condition quadratically helped guide a smarter pruning strategy, turning an expensive brute-force check into something efficient and elegant. #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
🚩 Problem: 239. Sliding Window Maximum 🔥 Day 51 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return an array containing the maximum value in every sliding window of size k. This is a classic sliding window problem that looks heavy, but with the right data structure, the solution is clean and O(n). 🧠 Intuition: A normal approach checks each window → O(n × k) (too slow). Instead, use a Deque to store indices of useful elements: The deque always keeps elements in decreasing order. The front of the deque is always the maximum of the current window. Remove elements: Outside the current window Smaller than the new incoming element This gives us the maximum in O(1) per window ⇒ total O(n). ⚙️ Performance: ⏱️ Runtime: 28 ms 🚀 💪 Beats: 98.7% of Java solutions 💾 Memory: 63 MB ⚡ (Beats ~96% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(k) ✨ Key Takeaway: The Deque technique is one of the most powerful sliding window optimizations — turning a potentially quadratic problem into linear time with a clean and elegant solution. Link:[https://lnkd.in/gJTzhcR2] #100DaysOfLeetCode #Day51 #Problem239 #SlidingWindowMaximum #Deque #SlidingWindow #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #CodingCommunity #ArjunInfoSolution #CodeNewbie #Programming #TechCareers #CareerGrowth #ZeroToHero #LearnToCode #CodingIsFun #ComputerScience #JavaDeveloper #DeveloperJourney #AI #MachineLearning #UnityGameDev #GameDeveloper
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 1513. 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐒𝐮𝐛𝐬𝐭𝐫𝐢𝐧𝐠𝐬 𝐖𝐢𝐭𝐡 𝐎𝐧𝐥𝐲 1𝐬 Today’s problem was a clean exercise in mathematical pattern recognition within strings — proving that sometimes, counting smartly beats looping endlessly. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given a binary string and need to count the number of substrings consisting entirely of '1's. Since the count can be large, the result is returned modulo 10⁹ + 7. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: The core insight is recognizing how consecutive '1's form substrings: For a group of k consecutive '1's, the number of valid substrings = k * (k + 1) / 2. Instead of explicitly using this formula, I used a simple iterative approach: Keep a running counter for consecutive '1's. Add that counter to the result whenever we encounter another '1'. Reset the counter on a '0'. This yields an elegant O(n) single-pass solution with constant space. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(1) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Mathematical series reasoning helps simplify substring problems. Consecutive counting avoids redundant substring generation. Simplicity and pattern recognition often lead to the most optimal logic. A great reminder that not every problem needs complexity — sometimes, it’s all about spotting the sequence. #LeetCode #DSA #Java #ProblemSolving #Algorithms #CodingPractice #LearningJourney #100DaysOfCode #Consistency #BinaryStrings
To view or add a comment, sign in
-
-
💡 LeetCode 2859 – Sum of Values at Indices With K Set Bits 💡 Today, I solved LeetCode Problem #2859, a clever mix of bit manipulation and array traversal that emphasizes how understanding binary representations can simplify computational logic. ⚙️ 🧩 Problem Overview: You are given a list of integers nums and an integer k. Your task is to find the sum of all elements at indices whose binary representation contains exactly k set bits (1s). 👉 Examples: Input → nums = [5,10,1,5,2], k = 1 → Output → 13 (Indices 1 and 2 have one set bit → nums[1] + nums[2] = 10 + 3) 💡 Approach: 1️⃣ Loop through all indices in the list. 2️⃣ Use Integer.bitCount(i) to count the number of set bits in the binary representation of each index. 3️⃣ If it equals k, add nums[i] to the sum. 4️⃣ Return the final total. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Linear scan of the list. ✅ Space Complexity: O(1) — Constant space usage. ✨ Key Takeaways: Strengthened understanding of bit-level operations using Java’s built-in methods. Reinforced how binary logic often leads to elegant and concise solutions. Demonstrated the power of combining mathematical reasoning with simple iteration. 🌱 Reflection: Bit manipulation is one of the most underrated yet powerful tools in problem-solving. This problem shows how thinking in binary can make complex conditions crystal clear — and the solution clean, efficient, and elegant. 🚀 #LeetCode #2859 #Java #BitManipulation #DSA #ProblemSolving #CodingJourney #AlgorithmicThinking #CleanCode #DailyPractice #ConsistencyIsKey
To view or add a comment, sign in
-
-
🔥 Day 35/100 of #100DaysOfCode - Finding Longest Sequence! Today's Problem: Longest Consecutive Sequence Task: Find the length of the longest consecutive elements sequence in an unsorted array. Solution: Used a HashSet for O(1) lookups! First added all elements to the set, then for each number, checked if it's the start of a sequence (no num-1 in set). If yes, counted consecutive numbers ahead. Key Insights: O(n) time complexity by only checking sequence starters HashSet eliminates duplicates and provides fast lookups Avoids O(n log n) sorting approach Smart Optimization: Only begins counting from sequence starting points Each number is processed at most twice (visited in set iteration + sequence counting) Handles duplicates and empty arrays gracefully Elegant solution that transforms an O(n²) brute force into O(n) using smart data structure choice! 💡 #100DaysOfCode #LeetCode #Java #Algorithms #HashSet #Arrays #CodingInterview
To view or add a comment, sign in
-
-
✅ Day 68 of LeetCode Medium/Hard Edition Today’s challenge was “Number of Ways to Form a Target String Given a Dictionary” — a brilliant Dynamic Programming and Combinatorics problem that tests precision in transitions and precomputation logic 🧩⚙️ 📦 Problem: You’re given an array of equal-length strings words and a target string target. You must form target from left to right by picking characters from the columns of words under these rules: 1️⃣ Once you use column k from any word, all columns ≤ k in every word become unusable. 2️⃣ You can use multiple characters from the same word, respecting column progression. Return the number of ways to form target modulo 1e9 + 7. 🔗 Problem Link: https://lnkd.in/gns9CwWa ✅ My Submission: https://lnkd.in/g7bsgZq9 💡 Thought Process: This problem is a clever mix of frequency compression and DP memoization. We precompute a frequency table freq[26][m], where each cell represents how many words contain a given letter at column m. Then, using recursion with memoization: 🎯 At each step (i, j) Either use freq[target[i]][j] if it exists → multiply by ways for the next position (i+1, j+1) Or skip the current column → move to (i, j+1) The recurrence relation: dp[i][j] = freq[target[i]][j] * dp[i+1][j+1] + dp[i][j+1] All computations are done modulo 1e9 + 7. ⚙️ Complexity: ⏱ Time: O(26 * n + t * m) — efficient due to frequency precomputation 💾 Space: O(t * m) — for memoized DP table 💭 Takeaway: This challenge reinforced how precomputation and state optimization can transform a seemingly exponential recursion into an elegant polynomial-time solution 🚀 #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #Combinatorics #ProblemSolving #Java #CodingChallenge #DSA
To view or add a comment, sign in
-
-
🚀 Day-75 of #100DaysCodeOfChallenge 💡 LeetCode Problem: 1526. Minimum Number of Increments on Subarrays to Form a Target Array (Hard) 🧠 Concepts Practiced: Greedy Algorithms | Array Manipulation | Difference Computation Today’s challenge was a Hard-level problem, focusing on finding the minimum number of operations required to transform an initial array of zeros into a given target array — using only subarray increments. The key insight here was realizing that each increase in value from one element to the next represents a required new operation on LeetCode. Instead of simulating every subarray operation, we can simply sum up the positive differences between consecutive elements — a great example of mathematical optimization through observation 💭 🔹 Intuition: Only when a number increases compared to the previous one, a new increment operation is needed. ⚙️ Language: Java ⚡ Runtime: 3 ms (Beats 100%) 💾 Memory: 56.82 MB (Beats 61.41%) ✅ Result: 129 / 129 test cases passed — Accepted! 🎯 Each “hard” problem solved adds one more layer of confidence — and reminds me that persistence pays off 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #Algorithms #CodingChallenge #GreedyAlgorithm #LearningJourney #TechMindset #KeepCoding #SoftwareEngineering #DeveloperLife #LogicBuilding
To view or add a comment, sign in
-
-
💻 𝐃𝐚𝐲 𝟖 / 𝟏𝟎𝟎 of "𝟏𝟎𝟎 𝐃𝐚𝐲𝐬 𝐨𝐟 𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞" Continuing my streak, today I solved "𝐌𝐚𝐱𝐢𝐦𝐮𝐦 𝐏𝐫𝐨𝐝𝐮𝐜𝐭 𝐨𝐟 𝐓𝐰𝐨 𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐬 𝐢𝐧 𝐚𝐧 𝐀𝐫𝐫𝐚𝐲" (LC - 1464). 🧩 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: Given an integer array nums, the goal is to find two elements such that the expression (nums[i] – 1) × (nums[j] – 1) is maximized. 🧠 𝐌𝐲 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Instead of sorting (which would take O(n log n)), I used a single-pass linear scan to track the two largest numbers in the array. Here’s how I approached it: - Initialize max and second_max as 0. - Traverse through the array once: - If the current number is greater than max, update both max and second_max. - Otherwise, update second_max if the current number is greater than it. - Finally, return (max - 1) * (second_max - 1). ⚙️ 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: This problem highlights how identifying patterns in operations (like needing only two maximums) can lead to a more efficient O(n) solution — eliminating unnecessary computation and improving performance. 💡 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐔𝐬𝐞𝐝: - Greedy approach - Array traversal - Optimization from O(n log n) → O(n) Every problem solved reaffirms how simplicity and efficiency often go hand in hand. 🚀 #Day8 #100DaysOfLeetCode #DSA #ProblemSolving #Java #CodingChallenge #GreedyAlgorithm #ContinuousLearning #edSlash #LeetCode edSlash LeetCode
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