🚀 Day 48 of #100DaysOfCode I recently tackled an interesting coding problem: “Given a binary number as a string, find the number of steps to reduce it to 1. If even, divide by 2; if odd, add 1.” For example: Input: "1101" → Output: 6 Input: "10" → Output: 1 Input: "1" → Output: 0 Instead of converting the binary to decimal, I simulated the steps directly on the binary string, which makes it efficient even for very long numbers. Here’s the Python solution I implemented: def numSteps(s: str) -> int: steps = 0 s = list(s) while len(s) > 1: if s[-1] == '0': s.pop() else: i = len(s) - 1 while i >= 0 and s[i] == '1': s[i] = '0' i -= 1 if i >= 0: s[i] = '1' else: s.insert(0, '1') steps += 1 return steps print(numSteps("1101")) # 6 💡 Key Takeaways: You can work directly with binary strings instead of converting them to integers. Simulating operations step by step is often more memory-efficient. This approach works even for very long binary strings (up to 500 bits in this problem). Coding challenges like this are a great way to sharpen algorithmic thinking! 🧠 #Python #CodingChallenge #BinaryNumbers #ProblemSolving #LeetCode #Algorithms
Binary Number Steps to 1 in Python
More Relevant Posts
-
200 LeetCode Problems I recently crossed the milestone of solving 200 problems on LeetCode, all implemented in Python. Working through Easy, Medium, and Hard challenges has helped me strengthen my coding skills, improve problem‑solving strategies, and gain confidence across different areas. Some of the key lessons from this journey include: 1. Using Python tools like Counter, defaultdict, and cmp_to_key effectively. 2. Implementing permutation problems and generating powersets with itertools.combinations. 3. Handling 32‑bit integer range constraints when required. 4. Applying binary search in creative ways — from rotated arrays to math problems like sum of squares. 5. Elegant tricks such as matrix transpose in one line with zip(*matrix). 6. Tackling 3Sum/4Sum using two‑pointer techniques and duplicate handling. 7. Leveraging prefix sums for problems like Push Dominoes and subarray challenges. 8. Using float('inf') and float('-inf') for boundary conditions. 9. Managing time and space complexity trade‑offs more effectively. Through these 200 problems, I’ve worked across: 1. Math & Number Theory (powers, squares, integer ranges) 2. Strings (palindromes, anagrams, permutations, custom sorting) 3. Arrays & Searching (binary search, rotated arrays, prefix sums, subarrays) 4. Hashing & Frequency (Counter, defaultdict, frequency maps) 5. Design & Implementation (HashMap, HashSet, Randomized set, TinyURL) 6. Classic Interview Problems (3Sum, 4Sum, Kth largest, Trapping Rain Water, Median of Two Sorted Arrays) This milestone is a reminder that consistent practice builds intuition, resilience, and confidence. Along the way, I’ve analyzed my progress and realized that I need to put more focus on prefix sums and subarray problems to strengthen my skills further. #LeetCode #PythonProgramming #ProblemSolving #Algorithms #DataStructures #CodingJourney #InterviewPreparation #ContinuousLearning #SoftwareEngineering #Learning #LogicalThinking
To view or add a comment, sign in
-
-
Day 41 of my #100DaysOfCode challenge 🚀 Today I implemented the Quick Sort algorithm in Python. Quick Sort is one of the most efficient and widely used sorting algorithms based on the divide-and-conquer approach. What the program does: • Takes an unsorted list as input • Selects a pivot element • Divides the list into three parts – Elements smaller than pivot – Elements equal to pivot – Elements greater than pivot • Recursively sorts the left and right parts • Combines everything into a sorted list How the logic works: • If the list has 1 or 0 elements, it is already sorted • A pivot element is selected (middle element in this case) • The list is divided into three parts: – left → elements less than pivot – middle → elements equal to pivot – right → elements greater than pivot • Recursively apply Quick Sort on left and right • Combine results: sorted = left + middle + right Example: Input: [3, 6, 8, 10, 1, 2, 1] Output: [1, 1, 2, 3, 6, 8, 10] Why Quick Sort is powerful: – Average Time Complexity: O(n log n) – Faster in practice than many sorting algorithms – Widely used in real-world applications Key learnings from Day 41: – Understanding pivot-based partitioning – Applying divide-and-conquer strategy – Writing recursive logic efficiently – Strengthening advanced DSA concepts #100DaysOfCode #Day41 #Python #PythonProgramming #QuickSort #SortingAlgorithms #DataStructures #Algorithms #DivideAndConquer #ProblemSolving #CodingPractice #InterviewPrep #LearnByDoing #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Day 35 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to count the number of words in a sentence without using the split() function. The goal was to understand how word detection works internally by scanning characters one by one. What the program does: • Takes a sentence as input • Iterates through each character • Detects transitions between spaces and words • Counts words manually without using split() • Handles punctuation and extra spaces How the logic works: •Two variables are initialized: – word_count to track the number of words – in_word to track whether we are currently inside a word •The program loops through each character in the sentence •If the character is alphanumeric (isalnum()): – It indicates part of a word – If we were not previously inside a word, the word count increases •If the character is not alphanumeric: – It marks the end of a word – in_word becomes False •This continues until the entire sentence is processed Example: Input: "Hello world! How are you?" Output: Word count → 5 Another example: Input: "This is a test sentence with extra spaces." Output: Word count → 8 Another example: Input: "One-two three." Output: Word count → 3 Why this approach is useful: – Shows how word counting works internally – Avoids built-in shortcuts – Handles punctuation and multiple spaces – Time Complexity: O(n) Key learnings from Day 35: – Parsing strings character by character – Using boolean flags to track state – Understanding how word boundaries work – Strengthening string processing logic #100DaysOfCode #Day35 #Python #PythonProgramming #StringProcessing #Algorithms #ProblemSolving #CodingPractice #LearnByDoing #ComputerScience #ProgrammingJourney #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Day 40 of my #100DaysOfCode challenge 🚀 Today I implemented the Merge Sort algorithm in Python. Merge Sort is a powerful divide-and-conquer algorithm that divides the list into smaller parts, sorts them, and then merges them back together. What the program does: • Takes an unsorted list as input • Recursively divides the list into halves • Sorts each half separately • Merges the sorted halves into a final sorted list How the logic works: • If the list has 1 or 0 elements, it is already sorted (base case) • The list is divided into two halves using the middle index • Each half is recursively sorted using merge_sort() • A helper function merge() combines the two sorted halves • Elements are compared and merged in sorted order • Remaining elements are appended after comparison Example: Input: [38, 27, 43, 3, 9, 82, 10] Output: [3, 9, 10, 27, 38, 43, 82] Why Merge Sort is powerful: – Time Complexity: O(n log n) – Efficient for large datasets – Stable sorting algorithm – Widely used in real-world applications Key learnings from Day 40: – Understanding divide-and-conquer strategy – Writing recursive functions – Merging sorted arrays efficiently – Moving towards advanced DSA concepts #100DaysOfCode #Day40 #Python #PythonProgramming #MergeSort #SortingAlgorithms #DataStructures #Algorithms #DivideAndConquer #ProblemSolving #CodingPractice #InterviewPrep #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Most people think AI agents are complex, mysterious systems. They're not. An agent is a thermostat. It reads a sensor (your prompt). It compares to a target (the task). It triggers an action (calls a tool). Then it waits and repeats. That's it. That's the architecture behind Claude Code, Cursor, and Copilot. The difference between understanding this and not? When it breaks, you know exactly which line caused it. We wrote a book that teaches you to build one from scratch in 750 lines of Python. No frameworks. No magic. Follow this page for more posts like this. https://lnkd.in/gWdFWM4g #AIAgents #Python #SoftwareEngineering #LLM
To view or add a comment, sign in
-
This metaphor changed how I explain AI agents to non-technical people. Once you say "thermostat," the mystique evaporates — and what's left is just engineering. That's why I wrote the book.
Most people think AI agents are complex, mysterious systems. They're not. An agent is a thermostat. It reads a sensor (your prompt). It compares to a target (the task). It triggers an action (calls a tool). Then it waits and repeats. That's it. That's the architecture behind Claude Code, Cursor, and Copilot. The difference between understanding this and not? When it breaks, you know exactly which line caused it. We wrote a book that teaches you to build one from scratch in 750 lines of Python. No frameworks. No magic. Follow this page for more posts like this. https://lnkd.in/gWdFWM4g #AIAgents #Python #SoftwareEngineering #LLM
To view or add a comment, sign in
-
Day 39 of my #100DaysOfCode challenge 🚀 Today I revisited and strengthened my understanding of the Insertion Sort algorithm in Python. Repetition is key in mastering Data Structures & Algorithms, so I reimplemented Insertion Sort to improve clarity and confidence. What the program does: • Takes an unsorted list as input • Iterates through elements one by one • Places each element at its correct position • Builds a sorted list step by step How the logic works: • Start from the second element of the list • Store the current element as key • Compare it with elements before it • Shift larger elements one position to the right • Insert the key at its correct position • Repeat until the entire list is sorted Example: Input: [12, 11, 13, 5, 6] Output: [5, 6, 11, 12, 13] Another example: Input: [64, 25, 12, 22, 11] Output: [11, 12, 22, 25, 64] Why revisiting algorithms matters: – Improves problem-solving speed – Strengthens conceptual clarity – Builds confidence for interviews – Helps write optimized code faster Key learnings from Day 39: – Reinforcing sorting algorithm concepts – Improving implementation accuracy – Practicing clean and readable code – Building consistency in DSA #100DaysOfCode #Day39 #Python #PythonProgramming #InsertionSort #SortingAlgorithms #DataStructures #Algorithms #ProblemSolving #CodingPractice #LearnByDoing #ComputerScience #ProgrammingJourney #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 18 / 100 — 100 Days of Code™: The Complete Python Pro Bootcamp Another step forward in the journey. Today’s milestone was mastering Graphical User Interfaces (GUI) and Algorithmic Art using Python’s Turtle module—and honestly, this is where the logic of programming meets the beauty of math. What stood out the most is how mathematical principles can be translated into clean, automated code. Instead of manually drawing every line, structuring the project into: • Modular functions like draw_shape • Dynamic RGB color generation • Algorithmic loops for complex patterns made it possible to create intricate designs like Spirographs and Random Walks with just a few lines of logic. 💡 Why Algorithmic Logic matters (real talk): When you use math (like the 360-degree method for polygons) to drive your code: ✅ Complex tasks become automated and simple ✅ Scaling from a triangle to a decagon requires zero extra effort ✅ Randomization (RGB & Direction) creates unique, data-driven results ✅ Logic becomes visual and easier to debug For example, if I want to: • Create a "Random Walk" with custom widths • Adjust the density of a Spirograph by changing the tilt angle • Generate a 50-step dashed line automatically • Or use the Turtle class to explore Object-Oriented principles I don’t need to draw every pixel—I just adjust the parameters of the function. That’s the real power of algorithmic thinking. This project reinforced something important for me: Creativity is just logic with a splash of color. Still early in the journey… but the consistency continues. 🔥 Day 18 of 100 — locked in. #100DaysOfCode #Python #TurtleGraphics #ProgrammingLogic #GUI #CreativeCoding #ProgrammingJourney #LearnInPublic #ConsistencyOverIntensity #DataJourney
To view or add a comment, sign in
-
Day 18: Scope and Precision — The Limits of Logic 🌐 As your programs grow, you'll start having variables with the same names in different places. How does Python know which one to use? And when doing math, how many decimals can Python actually "remember"? 1. Local vs. Global Scope Think of Scope as the "area of visibility" for a variable. Global Scope: Variables defined at the top level (outside any function). They can be read from anywhere in your script. Local Scope: Variables defined inside a function. They only exist while that function is running. Once the function ends, the variable is deleted. 💡 The Engineering Lens: Avoid using too many Global variables. If every function can change a variable, it becomes a nightmare to track down bugs. Keep data "Local" whenever possible! 2. The LEGB Rule: Python’s Search Engine When you call a variable name, Python searches in a very specific order to find it. This is the LEGB rule: Local: Inside the current function. Enclosing: Inside any nested "parent" functions. Global: At the top level of the file. Built-in: Python’s pre-installed names (like len or print). 3. Precision: The Decimal Limit When you use a Float (a decimal number), Python has to fit that number into a fixed amount of memory. Maximum Precision: Python floats are typically "double-precision" (64-bit). This means they can hold about 15 to 17 significant decimal digits. The Default: When you perform a calculation, Python will show as many decimals as are relevant, but it stops being accurate after that 15–17 digit mark. 💡 The Engineering Lens: Because of this limit, 0.1 + 0.2 often equals 0.30000000000000004. If you are building a banking app or a scientific tool where you need infinite precision, don't use floats! Use Python’s decimal module instead. #Python #SoftwareEngineering #CleanCode #ProgrammingTips #DataPrecision #LearnToCode #TechCommunity #PythonDev
To view or add a comment, sign in
-
𝗪𝗵𝘆 𝗜’𝗺 𝗧𝗿𝗲𝗮𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗶𝗸𝗲 𝗮 𝗖++ 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 🐍💻 Coming from a 𝗖++ 𝗯𝗮𝗰𝗸𝗴𝗿𝗼𝘂𝗻𝗱, I’m used to the computer doing exactly what I tell it to. Python, however, has a few “hidden” behaviors that caught me off guard in my first week of Harvard’s 𝗖𝗦𝟱𝟬𝗣. Using the 𝗙𝗲𝘆𝗻𝗺𝗮𝗻 𝗧𝗲𝗰𝗵𝗻𝗶𝗾𝘂𝗲 to solidify my learning, here are my top 3 “Aha!” moments from 𝗟𝗲𝗰𝘁𝘂𝗿𝗲 𝟬: 1️⃣ 𝗧𝗵𝗲 𝗶𝗻𝗽𝘂𝘁() 𝗧𝗿𝗮𝗽 In Python, input() always returns a string. ❌ The Bug: "10" + "5" → "105" ✅ The Fix: Cast to an integer: int(input()) 2️⃣ 𝗙-𝗦𝘁𝗿𝗶𝗻𝗴𝘀 = 𝗥𝗲𝗮𝗱𝗮𝗯𝗶𝗹𝗶𝘁𝘆 Forget messy concatenations. print(f"Hello, {name}") is clean, fast, and very Pythonic. It’s a masterclass in elegant output. 3️⃣ 𝗥𝗲𝘁𝘂𝗿𝗻𝘀 > 𝗦𝗶𝗱𝗲 𝗘𝗳𝗳𝗲𝗰𝘁𝘀 A function’s true power isn’t just printing to the screen—it’s 𝗿𝗲𝘁𝘂𝗿𝗻𝗶𝗻𝗴 𝗮 𝘃𝗮𝗹𝘂𝗲 your program can reuse. Reusability is the goal! ✨ 𝗙𝗶𝗻𝗮𝗹 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Code isn’t just for compilers—it’s for humans. If you can’t explain your logic simply, you haven’t fully mastered it yet. Excited to dive into 𝗖𝗦𝟱𝟬𝗣 𝗟𝗲𝗰𝘁𝘂𝗿𝗲 𝟭 and see what’s next! 🚀 #CS50P #Python #LearningInPublic #WomenInTech #ComputerScience #VirtualUniversity #ProgrammingJourney
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