🚀 #LeetCodePotd 68 — Binary Gap | ⚡ Runtime: 0 ms (100%) | #365DaysOfCode Cracked another clean bitwise problem today: 🔢 Binary Gap This is NOT a counting problem. It’s a position-tracking problem. Instead of converting to a string, we traverse bits directly and: Track the last position of 1 Compute difference when next 1 appears Update max distance That’s it. 📊 Complexity Analysis MetricValueTime ComplexityO(log n)Space ComplexityO(1) Why O(log n)? Because we process each bit once. No string conversion. No extra arrays. No unnecessary memory allocations. 🧠 What This Problem Actually Tests Bitwise operations mastery Invariant tracking Clean state management Avoiding unnecessary string overhead It’s an “Easy” question — but solving it with bit manipulation instead of string conversion shows maturity. 🏆 Submission Result ✔️ 261 / 261 testcases passed ⚡ Runtime: 0 ms (100%) 📦 Memory: 42.42 MB Small problem. Big mindset shift. 🎯 Takeaway Whenever a question says: “distance between occurrences” Think: Store last index Compute difference Update maximum That pattern appears in arrays, strings, and bit problems repeatedly. Consistent daily reps. Compounding bit by bit. Binary today, billionaire mindset tomorrow. 💪 #LeetCode #BinaryGap #DSA #DataStructures #Algorithms #BitManipulation #Java #Coding #Programming #SoftwareEngineer #TechCareers #InterviewPrep #ProblemSolving #CompetitiveProgramming #100DaysOfCode #WomenInTech #Developers #CodingLife #CodeNewbie #ComputerScience #TechCommunity #CodingJourney #FAANGPrep #PlacementPreparation
Cracking Binary Gap with Bitwise Operations
More Relevant Posts
-
UPDATE - 10 #CodingChallenge Hello everyone, Last week I spent time diving into Bit Manipulation, one of the most powerful yet underrated concepts in Data Structures & Algorithms. Here’s what I practiced: - Introduction to Bits and Bit Tricks - Checking if the i-th bit is set or not - Checking if a number is Odd or Even using bits - Checking if a number is a Power of 2 - Counting the number of Set Bits - Setting / Unsetting the rightmost unset bit - Swapping two numbers using XOR - Dividing numbers without multiplication or division operators Bit manipulation helps in solving problems by directly operating on the binary representation of numbers using bitwise operators like AND (&), OR (|), XOR (^), NOT (~), and bit shifts (<<, >>). It helped me in literally reducing time complexity in many problems, optimizes algorithms and it also very helpful in competitive programming as it reduces time very effectively. Learning these techniques showed me how powerful a few bitwise operations can be when solving complex problems efficiently. Example: We use condition '(n%2 == 0)' to check if even, but now we use '(n&1) == 0' and it is very much efficient. “Great programmers are not the ones who write the most code, but the ones who understand how the computer actually works.” "The Josh is High" 🫡 #DSA #StriverA2ZDSA #JAVA #DataStructures #Algorithms #ProblemSolving #CodingPractice #CodeDailyhashtag #LeetCode #SoftwareEngineering #DailyProgress #GrowthMindsetUPDATE #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 28/60 — LeetCode Discipline Problem Solved: Number of 1 Bits (Hamming Weight) Difficulty: Easy Today’s problem explored the fundamentals of bit manipulation, one of the most powerful and efficient areas in programming. The task was to count the number of set bits (1s) in the binary representation of a number. Instead of converting the number to a binary string, the solution uses bitwise operations to efficiently extract each bit. This approach highlights how low-level operations can lead to high-performance solutions with minimal overhead. 💡 Focus Areas: • Strengthened bit manipulation concepts • Practiced use of bitwise AND (&) • Understood right shift operations (>>>) • Improved efficiency by avoiding extra space • Built deeper understanding of binary representation ⚡ Performance Highlight: Achieved 0 ms runtime (100% performance). Mastering bits is like learning the language of machines — once you understand it, everything becomes faster and sharper. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #BitManipulation #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #TechGrowth #Consistency #LearnToCode
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 15/100 — Bitwise Navigation & State Tracking! Today’s Problem: 868. Binary Gap 🔹 The Goal: After yesterday’s focus on counting bits, today was about measuring the spatial relationship between them. Given an integer $n$, the task was to find the maximum distance between two consecutive "set bits" (1s) in its binary representation. 🔹 The Insight: Instead of converting the number to a String (which adds $O(N)$ space overhead), I treated the integer as a stream of bits. By using a sliding anchor approach, I could track the position of the last seen 1 and calculate the distance to the current 1 on the fly. 🔹 The Difficulty: The nuance lies in the "consecutive" requirement. You have to ignore the gaps until you've established a starting point. By initializing my lastPosition to -1, I created a "wait-and-see" state that ensures we only start measuring once a valid pair can be formed. ✨ Achievement: Another 0ms (100th percentile) submission! This problem reinforced how powerful bitwise operators like >> (right shift) and & 1 (masking) are for traversing data without needing extra data structures. 🔍 Steps followed: Bitwise Traversal: Iterated through the number using n >>= 1 to inspect each bit from right to left. Distance Calculation: Used a currentPosition counter to track our index and a lastPosition variable to "remember" where the previous 1 was. Max Update: Leveraged Math.max() to capture the largest gap discovered during the single pass. 🔧 Complexity Analysis: Time Complexity: $O(\log N)$. For a 32-bit integer, we perform at most 32 iterations, making this incredibly fast. Space Complexity: $O(1)$. No strings, no arrays—just a few primitive variables. The momentum is real. Moving from "what" bits are there to "where" they are located is sharpening my mental model for bit manipulation. 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #BitManipulation #Efficiency #Algorithms
To view or add a comment, sign in
-
-
Delegates in C# every new business rule meant writing another method that make The codebase grew. Everything looked the same. root of the problem was hardcoding behavior instead of designing for flexibility. Instead of writing ten methods that differ by one condition, you write one method and pass the behavior in from outside. The logic stays clean. The caller decides the rule. Nothing needs to be rewritten for every new case. Code Example: static List<Product> Search( List<Product> products, Func<Product, bool> filter ) => products.Where(filter).ToList(); // Here we put a second param takes a Func Delegation Search(catalog, p => p.Category == "Electronics"); Search(catalog, p => p.Price < 50); Search(catalog, p => p.Stock > 20); Search(catalog, p => p.Category == "Clothing" && p.Price < 100); // we search for products with different signatures with the same block of code Delegation achieve 3 critical points : 1. Eliminating repetition — One method handles every rule. No more cloning methods for every new condition. 2. Protecting core logic — Pass new behavior in, never rewrite what already works. 3. Behavior as a value — A rule becomes something you store, pass, and swap at runtime — not something locked inside a method. #CSharp #DotNet #SoftwareEngineering #CleanCode #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
Delegates in C# every new business rule meant writing another method that make The codebase grew. Everything looked the same. root of the problem was hardcoding behavior instead of designing for flexibility. Instead of writing ten methods that differ by one condition, you write one method and pass the behavior in from outside. The logic stays clean. The caller decides the rule. Nothing needs to be rewritten for every new case. Code Example: static List<Product> Search( List<Product> products, Func<Product, bool> filter ) => products.Where(filter).ToList(); // Here we put a second param takes a Func Delegation Search(catalog, p => p.Category == "Electronics"); Search(catalog, p => p.Price < 50); Search(catalog, p => p.Stock > 20); Search(catalog, p => p.Category == "Clothing" && p.Price < 100); // we search for products with different signatures with the same block of code Delegation achieve 3 critical points : 1. Eliminating repetition — One method handles every rule. No more cloning methods for every new condition. 2. Protecting core logic — Pass new behavior in, never rewrite what already works. 3. Behavior as a value — A rule becomes something you store, pass, and swap at runtime — not something locked inside a method. #CSharp #DotNet #SoftwareEngineering #CleanCode #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Day 22/60 — LeetCode Discipline Problem Solved: Reverse Integer (Revision) Difficulty: Medium Today’s practice focused on revisiting the classic integer manipulation problem — Reverse Integer. At first glance the problem appears straightforward: reverse the digits of a number. However, the real challenge lies in carefully handling edge cases such as integer overflow and maintaining correctness within the 32-bit signed integer range. Instead of using built-in conversions, the solution iteratively extracts digits and rebuilds the reversed number while ensuring that the result stays within valid bounds. 💡 Focus Areas: • Strengthened digit extraction using modulo operations • Practiced iterative number reconstruction • Handled integer overflow edge cases • Reinforced careful boundary condition checks • Focused on writing efficient and clean logic ⚡ Performance Highlight: Achieved ~99.9% runtime efficiency on submission. Revisiting foundational problems like this continues to sharpen attention to detail and improve algorithmic discipline. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Programming #Developers #TechCareers #Java
To view or add a comment, sign in
-
-
🚀 Day 86 / 100 – LeetCode Daily Challenge 📌 Problem: Minimize Number of Seconds to Complete Work (Heaps / PriorityQueue) Today’s problem was a great exercise in greedy optimization and priority-based scheduling! 🧠 Approach: Used a min-heap (PriorityQueue) to always pick the worker that can complete the next unit of work in the shortest time. Each worker’s time increases as they take on more tasks (1st unit: t[i], 2nd: 2*t[i], etc.), so the heap stores an array: [total time taken so far, worker index, number of units completed] The loop runs until all h units are assigned, and the final result is the last assigned completion time – which is the minimum total seconds needed. 📊 Result: ✅ 571 / 571 test cases passed ⚡ Runtime: 188 ms (beats 5.31%) – room for optimization, but it works! 💾 Memory: 47.84 MB (beats 15.17%) 📈 Key Takeaway: Even a brute-force heap simulation can give a correct solution, but optimizing the increment logic(e.g., using math to assign multiple units at once) would massively boost performance. Always think: Can I reduce heap operations? #100DaysOfCode #LeetCode #Java #PriorityQueue #Heaps #GreedyAlgorithms #CodingChallenge #ProblemSolving #SoftwareEngineering #TechJourney
To view or add a comment, sign in
-
-
⚡ Binary Logic at Scale: 0ms Performance Win! 🚀 I'm excited to share my latest solution for today's LeetCode challenge! I tackled the "Number of Steps to Reduce a Number in Binary Representation to One" and achieved a perfect 0 ms runtime, beating 100.00% of C++ submissions. 💡 The Strategy: Single-Pass Greedy Simulation Instead of performing heavy big-integer arithmetic, I simulated the reduction process by traversing the binary string from right to left (least significant to most significant bit): Handling Odds and Evens: For each bit, I considered the current carry. If the combined value (bit + carry) was 1, it represented an odd number requiring two steps (add 1 and then divide by 2). If it was 0 or 2, it required only one step. Carry Propagation: I maintained a carry variable to manage the "+1" operations across the string, ensuring the entire process remained O(N). Efficiency: This greedy approach avoids unnecessary string manipulations or divisions, resulting in the top-tier 0 ms execution time. 📊 Consistency Milestone: This win adds to my ongoing streak of high-performance solutions across: Bitwise Mastery: Reverse Bits, Alternating Bits, and Binary Gaps (all 0ms). Recursive Structures: 0ms wins in Binary Tree Traversals and Symmetry checks. Advanced Patterns: Custom sorting by bit counts and Segment Trees. Focusing on writing clean, compiler-friendly C++ is making these complex optimizations feel like second nature. 📈 . Check out the full implementation and my daily progress on GitHub: 📂 Repository: https://lnkd.in/gZ2v73xh . . . . #LeetCode #DSA #CPP #BinaryRepresentation #BitManipulation #Algorithms #ProblemSolving #SoftwareEngineering #CleanCode #Efficiency
To view or add a comment, sign in
-
-
𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝘀𝘁𝗮𝘁𝗶𝗰 𝗦𝘁𝗼𝗿𝗮𝗴𝗲 𝗖𝗹𝗮𝘀𝘀 𝗶𝗻 𝗖 💡 The 𝙨𝙩𝙖𝙩𝙞𝙘 storage class is one of the most powerful and unique tools because its behavior completely changes depending on where you define it. While other storage classes like 𝘢𝘶𝘵𝘰 or 𝘳𝘦𝘨𝘪𝘴𝘵𝘦𝘳 are straightforward, 𝙨𝙩𝙖𝙩𝙞𝙘 has a "split personality" that manages both memory lifetime and linking visibility. Here is the simple breakdown from this infographic: 🔒 𝟭. 𝘀𝘁𝗮𝘁𝗶𝗰 𝗶𝗻𝘀𝗶𝗱𝗲 𝗮 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 (𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗠𝗲𝗺𝗼𝗿𝘆) 𝗦𝘁𝗼𝗿𝗮𝗴𝗲 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆: Internal static storage. 𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲: Program-level. It is not destroyed when the function exits. 𝗦𝗰𝗼𝗽𝗲: Function/Block-level. It can only be seen and modified by that specific function. It's a private variable with a perfect memory! 🌐 𝟮. 𝘀𝘁𝗮𝘁𝗶𝗰 𝗼𝘂𝘁𝘀𝗶𝗱𝗲 𝗮 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 (𝗚𝗹𝗼𝗯𝗮𝗹 𝗙𝗶𝗹𝗲 𝗦𝗰𝗼𝗽𝗲) 𝗦𝘁𝗼𝗿𝗮𝗴𝗲 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆: Global static storage. 𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲: Program-level. Exists for the entire duration of the program. 𝗦𝗰𝗼𝗽𝗲: File-level. It is shared and can be changed by any function within that single .c file, but it is strictly hidden from functions in any other .c file in your project. It's like a family secret—shared with everyone inside the family (file) but hidden from outsiders (other files)! #CProgramming #EmbeddedSystems #Coding #SoftwareEngineering #StorageClass #LinkedInLearning
To view or add a comment, sign in
-
-
LeetCode Daily | Day 61 🔥 LeetCode POTD – 1009. Complement of Base 10 Integer (Easy) ✨ 📌 Problem Insight The complement of an integer is obtained by flipping all bits in its binary representation. ✔ 1 → 0 ✔ 0 → 1 Example: Input: n = 5 Binary: 101 Complement: 010 → Output: 2 ✅ 🔍 Initial Thinking – Convert to Binary String ❌ Idea: ✔ Convert the number to a binary string ✔ Flip each character (0 ↔ 1) ✔ Convert back to decimal ⚠ Problem: This involves extra conversions and string operations, which are unnecessary. 🔥 Optimized Approach – Bit Manipulation 💡 Key Idea Process each bit directly using bitwise operations. Steps: 1️⃣ Extract the last bit using n & 1 2️⃣ Flip it (1 → 0, 0 → 1) 3️⃣ Add it to the result with the correct power of 2 4️⃣ Shift n right to process the next bit Special Case: If n = 0, the complement is 1. ⏱ Complexity Time → O(log n) (number of bits) Space → O(1) 💡 Key Learning ✔ Bit manipulation can avoid unnecessary conversions ✔ n & 1 extracts the last bit efficiently ✔ Right shift (>>) helps process numbers bit-by-bit A simple but great reminder of how powerful bitwise operations can be in optimizing problems 🚀 #LeetCode #DSA #BitManipulation #Algorithms #CPlusPlus #ProblemSolving #CodingJourney
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