🚀 Day 45 of #100DaysOfCode ✅ Solved: Binary Gap (LeetCode 868) Today’s problem was about finding the longest distance between two consecutive 1s in the binary representation of a number. 🔎 Problem Insight: Given a positive integer n, convert it into binary and calculate the maximum distance between adjacent 1s. 💡 Key Idea: Instead of converting the number into a string, we can directly use bit manipulation: Traverse each bit using n & 1 Track the position of the previous 1 Update the maximum distance whenever a new 1 is found ⚡ Optimized Python Solution (O(log n) time | O(1) space) Python Copy code class Solution: def binaryGap(self, n: int) -> int: last = -1 max_dist = 0 position = 0 while n > 0: if n & 1: if last != -1: max_dist = max(max_dist, position - last) last = position n >>= 1 position += 1 return max_dist 🧠 What I Learned: Bitwise operations can make solutions more efficient Always think beyond string conversion for binary problems Tracking positions smartly reduces extra space usage Consistency > Motivation 🔥 One problem at a time towards mastering Data Structures & Algorithms. #LeetCode #ProblemSolving #Python #BitManipulation #DSA
Binary Gap Solution: LeetCode 868 with Bit Manipulation
More Relevant Posts
-
Day 9: Mastering the Two-Sum Strategy 🎯 💡 How I solved it: Instead of a slow O(n^2) nested loop to find pairs, I used a One-Pass Hash Map to achieve a lightning-fast O(n) solution. Target Calculation: For every number n, I calculated the diff (target - n) needed to complete the pair. Instant Lookup: I checked if this diff already existed in my prev_map. If it did, I immediately returned the indices. Dynamic Mapping: If the complement wasn't found, I stored the current number and its index {val: index} in the map to be used for future lookups. The Single Pass: This allowed me to find the answer in just one trip through the array. 🧠 Key Takeaway: Efficiency First: Trading a tiny bit of memory O(n) space for a massive gain in speed O(n) time is the hallmark of an optimized algorithm. Complement Logic: Learned that searching for a "pair" is really just searching for a "complement." Dictionary Power: This project reinforced how Python’s dictionary lookups are O(1) on average, making them the ultimate tool for reducing time complexity. One step closer to mastering Data Structures and Algorithms! 💻🔥 The logic is getting sharper every day! 📈🤝 #100DaysOfCode #DSA #Python #TwoSum #ProblemSolving #StriverA2ZSheet #CodingJourney
To view or add a comment, sign in
-
-
It’s not just a greeting. It changes based on real-time. Nstead of writing a basic print statement, I created a dynamic greeting program that changes according to the current time. 🛠 Tools & Concepts Used: ✅ Python ✅ time module ✅ Conditional statements (if-elif-else) ✅ Logical operators ✅ System time formatting 📌 What the Project Does: Detects current system time Displays: “Good Morning Sir” ☀️ “Good Afternoon Sir” 🌤 “Good Evening Sir” 🌙 Automatically adjusts greeting based on time range Visual preview below 🔗Full project(code +output): https://lnkd.in/dJyVFPy2 🔍 Actively building Python projects to strengthen my fundamentals. Feedback and suggestions are welcome 👇 #python #timemodule #vscode #aiml #datascientist #dataanalysis
To view or add a comment, sign in
-
-
🧠 Python Concept That Explains super() Magic: Cooperative Multiple Inheritance 💫 super() isn’t “call parent”. 💫 It’s “call next in MRO”. 🤔 The Surprise class A: def hello(self): print("A") class B(A): def hello(self): print("B") super().hello() class C(A): def hello(self): print("C") super().hello() class D(B, C): pass D().hello() ✅ Output B C A Why did C run? 🤯 🧠 Because super() follows MRO D → B → C → A Each class calls the next one. 🧒 Simple Explanation Imagine passing a message in line 👧👦👨 Each person: 💻 says their part 💻 passes to next 💻 That chain = cooperative inheritance. 💡 Why This Matters ✔ Multiple inheritance ✔ Framework mixins ✔ super() correctness ✔ Avoid duplicate calls ⚠️ Important Rule 🐍 Every class must use super() or chain breaks ❌ 🐍 super() isn’t about parents. 🐍 It’s about cooperation 🐍 Python classes form a chain — not a tree. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀Day 12 of #75DaysofLeetcode LeetCode #11 – Container With Most Water (Medium) Today I solved the classic Two Pointer problem: Container With Most Water. 🔎 Problem Summary: Given an array height, each element represents a vertical line. The goal is to choose two lines such that together with the x-axis they form a container that holds the maximum amount of water. 💡 Key Insight: Instead of checking all pairs (O(n²)), we can use the Two Pointer Technique: ✔ Start with one pointer at the beginning and one at the end ✔ Calculate the container area using area = min(height[left], height[right]) * (right - left) ✔ Move the pointer pointing to the smaller height ✔ Keep track of the maximum area ⚡ Optimal Complexity: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 💻 Python Implementation: from typing import List class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 max_water = 0 while left < right: area = min(height[left], height[right]) * (right - left) max_water = max(max_water, area) if height[left] < height[right]: left += 1 else: right -= 1 return max_water 📚 This problem reinforced how two pointers can reduce a brute force problem from O(n²) to O(n). Consistency in solving problems daily is slowly improving my problem-solving skills and algorithmic thinking. 💪 #LeetCode #DSA #Python #TwoPointers #ProblemSolving #CodingPractice #100DaysOfCode
To view or add a comment, sign in
-
-
That `InitVar` in a dataclass… do you actually know what it does? It looks like a field. It’s declared like a field. But it’s not really a field. In today’s video, I walk through 7 interesting things you can do with Python dataclasses. From automatic class registration and lightweight validation systems to cached derived values, self-building CLI parsers, and even using dataclasses as context managers. Most developers treat dataclasses like “nicer structs.” But they’re just normal Python classes with less boilerplate. And once you realize that, they become a design tool, not just a convenience. 👉 Watch the full video here: https://lnkd.in/e5pkc7Ae. #python #dataclasses #softwaredesign #cleancode #developers #arjancodes
To view or add a comment, sign in
-
-
🔥 Day 2 of #100DaysOfLeetCode 📌 Problem: Largest Number — Medium (#179) 🔗 https://lnkd.in/dzV8UhUc 💡 Approach: Normal sorting doesn't work here! The trick is to compare numbers by their concatenation. For "3" and "30" → compare "330" vs "303" → "330" wins → 3 comes first! Used Bubble Sort with a custom comparator — no extra libraries needed. 🐍 My Python Solution: nums = list(map(str, nums)) for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i]+nums[j] < nums[j]+nums[i]: nums[i], nums[j] = nums[j], nums[i] result = "".join(nums) return "0" if result[0]=="0" else result 📚 What I Learned Today: Sometimes the sorting key isn't the value itself — it's how two elements behave TOGETHER. Concatenation comparison is a powerful trick for number ordering problems! ⚡ Time : O(n²) — Bubble Sort 📦 Space : O(n) — String conversion #LeetCode #Python #DSA #100DaysOfLeetCode #100DaysOfCode #CodingJourney #DataScience #ProblemSolving #Programming #CS
To view or add a comment, sign in
-
-
𝗣𝘆𝘁𝗵𝗼𝗻 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗮𝘁𝘁𝗲𝗿𝗻𝘀 🐍 | 𝗦𝗲𝘁𝘀 – 𝗦𝗲𝘁 𝗠𝘂𝘁𝗮𝘁𝗶𝗼𝗻𝘀 🔄 | 📅 𝗗𝗮𝘆 𝟱𝟮 🚀 Today’s task: ✅ 𝗦𝘁𝗮𝗿𝘁 𝘄𝗶𝘁𝗵 𝗮 𝘀𝗲𝘁 A. ✅ 𝗣𝗲𝗿𝗳𝗼𝗿𝗺 𝗺𝘂𝗹𝘁𝗶𝗽𝗹𝗲 𝘀𝗲𝘁 𝗼𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀. ✅ 𝗨𝗽𝗱𝗮𝘁𝗲 𝘁𝗵𝗲 𝘀𝗲𝘁 𝗱𝗶𝗿𝗲𝗰𝘁𝗹𝘆. ✅ 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 𝗽𝗿𝗶𝗻𝘁 𝘁𝗵𝗲 𝘀𝘂𝗺 𝗼𝗳 𝗲𝗹𝗲𝗺𝗲𝗻𝘁𝘀. Operations used: • update() • intersection_update() • difference_update() • symmetric_difference_update() Simple? Only if you understand set mutation vs set operation. Core idea from the code: Instead of creating new sets, these operations modify the original set directly. Example: A.update(B) → adds elements of B into A A.intersection_update(B) → keeps only common elements A.difference_update(B) → removes elements present in B A.symmetric_difference_update(B) → keeps elements not common in both 💡 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Mutation operations are important when: • You want memory-efficient updates • You want to modify the original dataset • You want faster in-place operations Because strong Python developers don’t just know operations. They understand when data is modified vs copied. Cleaner logic. Better performance. #Python #Sets #InterviewPrep #HackerRank #DataStructures #ProblemSolving #DailyCoding #Consistency
To view or add a comment, sign in
-
-
That `InitVar` in a dataclass… do you actually know what it does? It looks like a field. It’s declared like a field. But it’s not really a field. In today’s video, I walk through 7 interesting things you can do with Python dataclasses. From automatic class registration and lightweight validation systems to cached derived values, self-building CLI parsers, and even using dataclasses as context managers. Most developers treat dataclasses like “nicer structs.” But they’re just normal Python classes with less boilerplate. And once you realize that, they become a design tool, not just a convenience. 👉 Watch the full video here: https://lnkd.in/eeEzkhJQ. #python #dataclasses #softwaredesign #cleancode #developers #arjancodes
To view or add a comment, sign in
-
-
Day 6 of #60DaysOfMiniProjects From image processing and QR decoding to building structured command-line applications — growing one step at a time. Today I built a CLI-based TODO List using Python What this project does: • Displays a simple menu-driven interface • Adds tasks dynamically • Stores tasks using lists • Displays tasks with proper numbering • Uses loops to keep the program running Concepts I worked with: • Lists and data storage • While loops for continuous execution • Conditional statements • Enumerate for clean indexing • Writing cleaner, user-friendly CLI programs Moving from small scripts to interactive programs. Building logic. Strengthening fundamentals. Small projects. Real concepts. Daily progress. Consistency builds confidence. #Python #MiniProjects #BuildInPublic #CodingJourney #CSE #DeveloperGrowth #LearningInPublic
To view or add a comment, sign in
-
Some instructions are used more than once. When working with data, certain operations tend to repeat. Cleaning a value. Checking a condition. Transforming a piece of information. Applying the same rule across different parts of a dataset. Writing the same set of instructions every time would quickly make code longer and harder to follow. This is where functions come in. A function is simply a way of grouping a set of instructions under a name so that the same logic can be used again whenever it is needed. Instead of rewriting the steps, the program calls the function and runs those instructions again. For example: def check_pass(score): if score >= 50: return "Pass" return "Fail" Once defined, the same logic can be applied wherever it is needed. check_pass(72) check_pass(43) The instructions stay the same. Only the input changes. Functions don’t introduce new logic. They organize existing logic so it can be reused clearly and consistently. And in larger programs, that organization becomes just as important as the logic itself. Day 28 / 30. #30DaysOfDataScience #Python #Functions #ProgrammingLogic #LearningInPublic
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