Day 2/100 of my LeetCode Challenge🚀 Problem of the Day #868: Binary Gap - Finding gaps in binary representations! Today's problem was deceptively simple but had an elegant bit manipulation solution. The Challenge: Given a positive integer, find the longest distance between any two adjacent 1's in its binary representation. Instead of converting to string and storing all positions in a list (which works but wastes space), we can track only the previous 1's position while scanning bits from right to left. Key Insights: - Bit manipulation (n & 1, n >>= 1) is more efficient than string conversion - We only need to track consecutive 1's, not all pairs - Time complexity: O(log n), Space: O(1) What I Learned: Sometimes the most intuitive solution (convert to string, store positions) isn't the most optimal. Thinking in bits can lead to cleaner, more efficient code! #leetcode #bitmanipulation #100DaysOfCode
Binary Gap Challenge: Efficient Bit Manipulation Solution
More Relevant Posts
-
Finally wrapped up LeetCode Weekly Contest 490 and managed to clear all 4 questions! Honestly, today's problem set was a solid mix of pure logic and classic DP. Here is a quick breakdown of how I tackled them: Q1 (Simulation): Straightforward game simulation. I kept it simple by using a boolean flag to track the active player, swapped their turns based on the given conditions, and subtracted their final results at the end. Q2 (Permutations & Frequencies): This was an interesting frequency counting problem. I used two hash maps: one to store the digit count of the factorial, and the second for the digits of the given integer n. If the maps matched, it returned True, else False. Q3 (Bit Manipulation): Bit logic came in clutch here. Since XORing different bits gives 1 and the same bits gives 0, I stored the bit count of string t in a map, and then populated the result by traversing string s. Q4 (3-State Recursion/DP): The classic "figure out the states" challenge. I realized pretty quickly it was a 3-state recursion problem. Since a pure recursive approach wasn't optimal and would cause a Time Limit Exceeded (TLE), I added memoization to cache the overlapping subproblems and optimize the solution perfectly. #LeetCode #CompetitiveProgramming #Algorithms #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
-
Day 62 of LeetCode Grind ⚡🔥 Back after a while — I got pulled into a research project that's been consuming all my bandwidth. More on that soon. But the grind never fully stops. Problem: Find All Possible Stable Binary Arrays II (3130) — HARD Count arrays with exactly zero 0s and one 1s where no subarray of length > limit is uniform. Result modulo 10⁹ + 7. > Runtime: 35ms — beats 99.98% 🔥 💡 Core Insight: Combinatorics + Inclusion-Exclusion * Instead of DP on states, this solution frames the problem as distributing runs of identical characters into slots — a pure combinatorics approach. Key building block — ways(n, k): * Think of placing n identical elements into k non-empty groups (runs), where each group has size ≤ limit. By stars and bars, without the limit constraint, it's simply C(n-1, k-1). To enforce the upper bound per group, apply inclusion-exclusion: << ways(n, k) = Σ (-1)^j * C(k, j) * C(n - j*limit - 1, k - 1) >> This subtracts cases where at least j groups exceed limit. How the answer is assembled: * We fix the number of runs of 0s as k (ranging from the minimum needed to zero). * The number of runs of 1s must be k-1, k, or k+1 depending on which end the array starts/ends on. * That's why the sum weighs ways(one, k-1) + 2*ways(one, k) + ways(one, k+1) — the 2x middle term accounts for both orderings where runs interleave symmetrically. * A sliding window (prv, cur, nxt) maintains these three consecutive ways(one, *) values efficiently. * Precomputed factorials + modular inverses make each C(n, r) call O(1), so the whole solution runs in effectively O(zero / limit) iterations — hence the blazing 35ms! Complexity: * Precomputation: O(MAXN) * Main loop: O(zero/limit × MAXN/limit) with memoized ways * Space: O(MAXN + memo) ✨ Reflection: This is one of those problems where DP feels natural but combinatorics wins on performance. Recognizing that "stable arrays = distributing runs with bounded sizes" reduces the problem to textbook inclusion-exclusion on integer partitions. Once that click happens, the rest falls into place. * The ways.cache_clear() at the end is a nice touch too — keeps repeated calls across test cases from ballooning memory in competitive settings. Missed a few posts but the streak of solving continues internally. Research has been wild — will share more when the time is right. Back to regular posting now! 💪 #LeetCode #Day62 #Combinatorics #InclusionExclusion #DynamicProgramming #ModularArithmetic #Python #99thPercentile #100DaysOfCode #Research #BackToGrind
To view or add a comment, sign in
-
-
Day 32 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Most Frequent Character in a String We were given a string s. All characters are lowercase. Task was to find the character with maximum frequency. If multiple characters have same frequency, return the lexicographically smaller one. Example: "testsample" → e 💻 Approach 🔹️Create a frequency array of size 26. 🔹️Traverse the string and count each character. 🔹️Find the character with maximum frequency. 🔹️If frequencies are same, pick smaller character. Simple counting logic. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) Fixed array of size 26. 📚 What I learned today: ▫️Frequency arrays are very useful for string problems. ▫️Handling tie conditions (lexicographic order) is important. ▫️Constant space solutions are possible with fixed character sets. ▫️Careful comparison logic matters in final result. Day 32 completed. Improving string handling step by step 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Day 64/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 189 – Rotate Array (Medium) 🧠 Approach: Use the array reversal technique. Reverse the entire array Reverse the first k elements Reverse the remaining elements This rotates the array in-place. 💻 Solution: class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) k = k % n def reverse(l, r): while l < r: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 reverse(0, n - 1) reverse(0, k - 1) reverse(k, n - 1) ⏱ Time | Space: O(n) | O(1) 📌 Key Takeaway: Reversal is a powerful in-place technique for solving array rotation problems efficiently. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
100 Days of LeetCode Challenge- Day 89 Problem: Remove All Adjacent Duplicates in String Problem Definition Given a string s, repeatedly remove adjacent duplicate characters until no duplicates remain. Return the final string after all such removals. Example: Input: s = "abbaca" Output: "ca" Explanation: Remove "bb" → "aaca" Remove "aa" → "ca" Approach I used a stack-based approach to track characters. Steps: Traverse each character in the string. If the stack is not empty and the top element equals the current character, remove the top element. Otherwise, push the current character into the stack. After processing the entire string, build the result from the stack. This efficiently removes adjacent duplicates as they appear. Time Complexity O(n) — Each character is pushed and popped at most once. Space Complexity O(n) — Stack used to store characters. . #Day89 #100DaysOfCode #LeetCode #Stack #DataStructures #ProblemSolving
To view or add a comment, sign in
-
-
#100DaysLeetCode Day 32 ✅ Solved LeetCode 169: Majority Element The task is to find the element that appears more than ⌊n/2⌋ times in the array. 🚀 Approach Used the Boyer–Moore Voting Algorithm. Idea: Maintain a candidate (majority element) and a count. If count becomes 0, update the candidate. If current element equals candidate → increase count. Otherwise → decrease count. Because the majority element appears more than half of the time, it will remain the final candidate. Time Complexity: O(n) Space Complexity: O(1) #100DaysLeetCode #Day32 #LeetCode169 #leetcode #cpp #dsa #arrays #algorithm #problemSolving #coding #interviewprep
To view or add a comment, sign in
-
-
𝟵 𝗱𝗮𝘆𝘀 𝗼𝗳 𝘀𝗵𝗼𝘄𝗶𝗻𝗴 𝘂𝗽. 𝟵 𝗱𝗮𝘆𝘀 𝗼𝗳 𝘀𝗼𝗹𝘃𝗶𝗻𝗴. 𝟵 𝗱𝗮𝘆𝘀 𝗼𝗳 𝗴𝗲𝘁𝘁𝗶𝗻𝗴 𝗯𝗲𝘁𝘁𝗲𝗿. 🚀 Today’s LeetCode POTD, "3129. Find All Possible Stable Binary Arrays I," was a masterclass in recursive thinking with memoization. The challenge? Building a binary array with an exact number of zeros and ones while ensuring no subarray exceeds the "limit" without a bit flip. The beauty of this problem lies in managing the state—tracking how many 0s and 1s are left while respecting the stability constraint. I opted for a Recursion + Memoization approach with a Time Complexity of $O(\text{one} \cdot \text{zero} \cdot \text{limit})$. It feels good to see that "Accepted" screen, especially when your memory usage beats 94% of other submissions! Consistency is the only "cheat code" in this game. How are you staying consistent with your coding goals this month? Let’s talk strategy in the comments! 👇
To view or add a comment, sign in
-
-
HI CONNECTIONS I recently tackled LeetCode 3010, a problem that perfectly illustrates how "greedy" logic can simplify a seemingly complex array partition task. 🔍 The Challenge Divide an array into 3 subarrays such that the sum of their first elements is minimized. Constraint: The first subarray must start at index 0. 🛠️ The Strategy: Finding the "Cheapest" Starts Since the first subarray always starts at nums[0], the problem reduces to finding the two smallest values in the remaining part of the array to serve as the starting points for the other two subarrays. Fixed Cost: Start with cost = nums[0]. Search: Scan the remainder of the array (nums[1] to nums[n-1]). Optimize: Identify the two smallest elements (min1 and min2). Total: Total Cost = nums[0] + min1 + min2. 📊 Performance Time Complexity: O(n) — A single pass to find the two smallest numbers. Space Complexity: O(1) — No extra data structures needed. 💡 Key Takeaway Sometimes, the most efficient solution isn't about complex partitions or Dynamic Programming—it's about identifying which variables are fixed and optimizing the rest. #LeetCode #Algorithms #ProblemSolving #CleanCode #Optimization #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 57/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 260 – Single Number III (Medium) 🧠 Approach: Since every element appears twice except two numbers, return the numbers whose frequency is 1. 💻 Solution: class Solution: def singleNumber(self, nums: List[int]) -> List[int]: if len(nums)==2: return nums ele = [] d = {} for i in nums: d[i] = d.get(i,0)+1 for i in d: if d[i]==1: ele.append(i) return ele ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Frequency counting is a straightforward way to identify unique elements in an array. #leetcode #dsa #development #problemSolving #CodingChallenge
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