š Solved LeetCode 3234: Count Substrings with Dominant Ones! š§ Just tackled a challenging substring problem: 3234. Count the Number of Substrings With Dominant Ones. The goal is to find all substrings where the count of '1's is greater than or equal to the square of the count of '0's. A simpleĀ O(N²)Ā approach is too slow, so a more optimized strategy is needed. My Approach: Key Insight:Ā The conditionĀ ones >= zeros² means the number of zeros in any valid substring is small (at mostĀ āN). This is the key to optimization. Fix the Endpoint:Ā I iterate through the string, fixing theĀ endĀ of the potential substring. "Zero-Hopping" Technique:Ā From theĀ end, I iterate backward, but instead of going one by one, I "hop" from each '0' to the previous '0'. A precomputed array makes this hopĀ O(1). Efficient Counting:Ā At each hop, I calculate the number of valid start positions in the segment between the two zeros, bringing the total time complexity down toĀ O(NāN). This was a great puzzle in finding the bottleneck and building an algorithm around it! šĀ Problem Link:Ā https://lnkd.in/gpmZdskg #LeetCode #Coding #Algorithm #Python #ProblemSolving #SoftwareEngineering #Optimization #LeetCode #Coding #Algorithm #Python #Programming #InterviewPrep
Solved LeetCode 3234: Count Dominant Ones Substrings
More Relevant Posts
-
š” Day 37 of 100 ā Minimum Operations to Convert All Elements to Zero (#LeetCode 3542) Todayās problem was an interesting one short in code, but deeper in logic. It was one of those problems where the intuition slowly unfolds as you play with examples. š§ What I figured out This problem is all about monotonic stacks a pattern that helps you process elements in increasing or decreasing order efficiently. The key idea: Every time the current number is greater than whatās on top of the stack, it represents a new āoperationā needed. By maintaining a non-decreasing stack, you avoid unnecessary repetitions and count exactly when new operations are required. š» My thought process At first, I tried to simulate each operation directly which got messy. Then I realized this could be solved cleanly using a stack that tracks when a new increase appears in the sequence. Every rise means one more operation, and when numbers fall, you just pop from the stack. š Complexity: Time ā O(n) Space ā O(n) š¬ Reflection This one reminded me how often elegant ideas hide in short problems. Itās not about long code itās about clarity of thought. Sometimes, a single stack can tell the whole story. #100DaysOfLeetCode #Day37 #LeetCodeJourney #Coding #ProblemSolving #Python #DSA
To view or add a comment, sign in
-
-
š Product of Array Except Self ā LeetCode #238 Today, I solved one of the most elegant problems in array manipulation ā āProduct of Array Except Self.ā š§© Problem in short: Given an integer array nums, return an array answer such that answer[i] equals the product of all numbers in nums except nums[i], ā Without using division ā In O(n) time ā With O(1) extra space š” Key Insight ā Prefix & Suffix Products Instead of recalculating every product, the trick is to use two passes: First pass: Store the product of all elements before each index (prefix). Second pass: Multiply each element by the product of all elements after it (suffix). This way, each position in the output represents the product of all other elements ā efficiently and elegantly. āļø Complexity Time: O(n) Space: O(1) (excluding the result array) š Result ā Accepted ā Runtime: 20 ms ā” Beats 74.21% in performance and 55.22% in memory usage Every problem like this reinforces one key principle: In interviews (and real-world problems), pattern recognition always beats rote memorization. This one beautifully highlights the PrefixāSuffix Pattern, seen in problems like Trapping Rain Water and Subarray Product. #LeetCode #DSA #CodingInterview #Python #Arrays #PrefixSuffix #ProblemSolving
To view or add a comment, sign in
-
-
Problem: Given a string containing ()[]{}, determine if the parentheses are valid. A string is valid if brackets close in the correct order and type. ā¬ļø ā¬ļø ā¬ļø My initial intuition: š Thought of using a stack immediately ā push openings, pop on closings. ā ļø But the first few implementations broke on tricky cases like ([)]. 𤔠I was popping and comparing in the wrong order and couldnāt figure out how to validate the pairings cleanly. ā¬ļø ā¬ļø ā¬ļø After careful debugging: š Discovered that flipping my mapping made the logic much simpler: { ')': '(', ']': '[', '}': '{' } š” This way, every closing bracket directly tells me which opening it expects. š The stack now works perfectly ā last in, first out ā catching even the toughest edge cases. ššš learned about little micro optimizations: -> to create a local reference of the map helps with access times. -> not unravelling map with .values() calls, instead created a set of opening parenthesis. ā Intuition was right this time. š Execution... not so much. #LeetCode #ProblemSolving #Python #LearningJourney #Coding
To view or add a comment, sign in
-
-
š DSA Challenge ā Day 80 Problem: Maximum Distance Between Valid Pairs šš Todayās problem tested the combination of binary search and array monotonicity ā finding the farthest valid pair between two non-increasing arrays! š§ Problem Summary: Weāre given two non-increasing arrays, nums1 and nums2. A pair (i, j) is valid if: i ⤠j, and nums1[i] ⤠nums2[j]. The goal is to find the maximum distance (j - i) among all valid pairs. āļø My Approach: 1ļøā£ Iterate through each element in nums1. 2ļøā£ Use binary search on nums2 to find the farthest valid index satisfying the condition. 3ļøā£ Keep track of the maximum j - i distance encountered. This solution leverages the sorted (non-increasing) property of arrays for logarithmic efficiency. š Complexity: Time: O(n log m) ā For each element in nums1, a binary search on nums2. Space: O(1) ā Only a few variables used. ⨠Key Takeaway: Sometimes, monotonic properties allow you to blend binary search with iteration ā turning what looks like a brute-force problem into a clean and efficient search-based solution. ā” š #DSA #100DaysOfCode #LeetCode #ProblemSolving #Algorithms #BinarySearch #TwoPointers #CodingChallenge #Python #InterviewPrep #TechCommunity #Optimization #EfficientCode #CodeEveryday
To view or add a comment, sign in
-
-
Day 62: Recover Binary Search Tree (BST) š³ I'm continuing my journey onĀ Day 62 of #100DaysOfCodeĀ with a challenging BST problem:Ā "Recover Binary Search Tree."Ā The task is to fix a BST where exactly two nodes have been swapped by mistake, all without changing the tree's structure. The key insight relies on the property ofĀ Inorder TraversalĀ of a BST, which always yields nodes inĀ ascending order. Inorder Traversal:Ā I first perform a standard inorder traversal (using recursion) to store the node values in an ascending list (inorder). Finding Swapped Nodes:Ā I then iterate through theĀ inorderĀ list to find the two misplaced nodes. A violation occurs whenĀ inorder[i-1] > inorder[i]. TheĀ firstĀ misplaced node (first) is the larger element of the first violation. TheĀ secondĀ misplaced node (second) is the smaller element of the last violation. Correction:Ā Finally, I swap the values of the two nodes found in the original tree. This method achieves anĀ O(n) time complexityĀ andĀ O(n) space complexityĀ (due to storing the inorder array). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #BST #InorderTraversal #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
Day 39 / 100 ā Combination Sum (LeetCode #39) Todayās challenge was Combination Sum, a classic problem that teaches how to explore all possible combinations that add up to a target. The key idea here is recursion with backtracking ā trying different paths, and āundoingā choices when they donāt lead to a solution. At first, it felt complex to keep track of combinations without duplicates, but recursion made it elegant once I understood how to structure the calls properly. Itās a great example of how backtracking mirrors human problem-solving: try, fail, and refine until success. š Key Learnings Recursion helps break complex problems into smaller, reusable patterns. Backtracking avoids unnecessary computation by pruning invalid paths early. Always remember to copy the current combination when adding it to results ā lists are mutable! š Thought of the Day Sometimes the most powerful solutions come from simplicity ā recursion mirrors the way we naturally think through problems step by step. Todayās problem reminded me that patience and clarity often lead to clean, beautiful solutions ⨠š Problem Link: https://lnkd.in/gxtE573Z š·ļø #100DaysOfCode #Day39 #LeetCode #Python #Recursion #Backtracking #ProblemSolving #Algorithms #DataStructures #CodingChallenge #LearnToCode #CleanCode #MindsetMatters #CodeEveryday #TechJourney
To view or add a comment, sign in
-
-
Day 72: Partition List š I'm back to linked lists onĀ Day 72 of #100DaysOfCodeĀ by solvingĀ "Partition List."Ā The challenge is to rearrange a linked list around a valueĀ x, such that all nodes less thanĀ xĀ come before all nodes greater than or equal toĀ x, while preserving the original relative order within each partition. My solution uses aĀ two-list approachĀ with dummy nodes: Creation of Two Lists:Ā I initialize two separate dummy nodes:Ā less_dummyĀ andĀ greater_dummy. Partitioning:Ā I iterate through the original list once. If a node's value is less thanĀ x, I append it to theĀ lessĀ list; otherwise, I append it to theĀ greaterĀ list. This inherently preserves the relative order within each group. Merging:Ā After the single pass, I set theĀ nextĀ pointer of the tail of theĀ lessĀ list to the head of theĀ greaterĀ list (less_tail.next = greater_dummy.next). Crucially, I set the tail of theĀ greaterĀ list toĀ NoneĀ to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimalĀ O(n) time complexityĀ andĀ O(1) extra space complexityĀ (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
Day 36 / 100 ā Longest Palindromic Substring (LeetCode #5) Todayās challenge focused on String Manipulation ā finding the longest palindromic substring within a given string. At first, it felt tricky to handle all the possible substrings, but then I learned to expand around the center, checking for symmetry on both sides. This approach makes the solution both logical and efficient. This problem reinforced how clarity in logic often comes from recognizing patterns, and that even complex problems can be broken into smaller, mirror-like checks. š Key Learnings Expanding around the center efficiently checks for palindromes in O(n²) time. Always consider both even and odd length palindromes. String problems often rely on clear thinking more than heavy algorithms. š Thought of the Day Problem-solving isnāt about rushing for the answer ā itās about exploring the structure of the challenge. Palindromes taught me patience, symmetry, and the art of looking for balance in both logic and code. š Problem Link: https://lnkd.in/gSe-ygD8 #100DaysOfCode #Day36 #LeetCode #Python #StringManipulation #ProblemSolving #Algorithms #CodingChallenge #CleanCode #CodeEveryday #LearningJourney #DataStructures #Optimization
To view or add a comment, sign in
-
-
š DSA Challenge ā Day 85 Problem: Check if All Integers in a Range Are Covered ā š This problem was an elegant use of the Prefix Sum technique, where I used range updates to efficiently check coverage over an interval. š§ Problem Summary: You are given several inclusive integer intervals and a target range [left, right]. You must verify if every integer within [left, right] is covered by at least one of the given intervals. āļø My Approach: 1ļøā£ Initialize an array line to track coverage at each integer position. 2ļøā£ For every range [a, b], increment line[a] and decrement line[b + 1] ā this marks the start and end of coverage. 3ļøā£ Convert line into a prefix sum array, so each position reflects how many intervals cover that number. 4ļøā£ Finally, iterate through [left, right] to ensure each integer has coverage (> 0). š Complexity: Time: O(n + 52) ā Linear scan and prefix sum computation. Space: O(52) ā Fixed-size array since ranges are small. ⨠Key Takeaway: Prefix sum is not just for subarray sums ā itās a powerful trick for range marking and coverage problems, offering O(1) updates and O(n) verification. ā” š #DSA #100DaysOfCode #LeetCode #PrefixSum #RangeUpdate #ProblemSolving #Algorithms #CodingChallenge #Python #EfficientCode #Optimization #TechCommunity #InterviewPrep #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
-
š§ Day 13 ā Thinking in Ranges, Not Just Numbers Todayās LeetCode problem was āMaximum Frequency of an Element After Performing Operations I.ā At first, it felt straightforward ā perform up to numOperations changes on elements within a range of [-k, k] to maximize frequency. But once I got into it, I realized the real challenge wasnāt the operations ā it was understanding how intervals overlap and interact. Hereās the logic I built around it: š¹ Each number can shift within [num - k, num + k], forming a range of possible values. š¹ The goal is to find how many such ranges overlap at any point ā that overlap represents the maximum achievable frequency. š¹ I used sorted events and a sweep line approach to track how many intervals are active at any moment. š¹ The maximum overlap gives the answer ā the highest number of elements that can become equal after allowed operations. This problem wasnāt just about code; it was about thinking visually ā seeing numbers as segments on a line rather than static values. That shift in perspective changed how I approached it. Thanks to Shishir chaurasiya sir and PrepInsta team One more day, one more layer of understanding peeled back. #Day13 #LeetCode #ProblemSolving #100DaysOfCode #Python #Algorithms #DataStructures #KeepBuilding #DevMindset
To view or add a comment, sign in
-
Explore related topics
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