🚀 LeetCode Practice 📌 Problem: Number of Steps to Reduce a Number in Binary Representation to One 🔗 LeetCode Problem #1404 🧠 Problem Statement Given a binary string s, return the number of steps required to reduce it to "1" using: ✅ If the number is even → divide it by 2 ✅ If the number is odd → add 1 It is guaranteed that we can always reach "1". 🔎 Example Input: s = "1101" Output: 6 Explanation: 13 (1101) → +1 → 14 14 → /2 → 7 7 → +1 → 8 8 → /2 → 4 4 → /2 → 2 2 → /2 → 1 💡 Key Insight The length of s can be up to 500 bits, so converting directly to an integer might not be ideal in some languages. Instead, we: Traverse from right to left Simulate division and addition Maintain a carry variable Count operations efficiently ⚡ Optimized Approach (Greedy + Carry Handling) 🔥 Core Observations If last bit is '0' → number is even → 1 step (divide) If last bit is '1' → number is odd → 2 steps (add 1 + divide) Handle carry propagation carefully 🧑💻 Python Implementation (O(n) Time | O(1) Space) class Solution: def numSteps(self, s: str) -> int: steps = 0 carry = 0 # Traverse from right to left (ignore MSB) for i in range(len(s) - 1, 0, -1): bit = int(s[i]) # If bit + carry == 1 → odd if bit + carry == 1: steps += 2 carry = 1 else: steps += 1 return steps + carry 📊 Complexity Analysis ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Where n is the length of the binary string. #LeetCode #ProblemSolving #Python #DSA #CodingInterview #BitManipulation #TechGrowth
Reduce Binary to 1 Steps
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 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
To view or add a comment, sign in
-
-
A hands-on collection of real-world implementations to build LLM-powered applications using Python, LangChain, and Hugging Face. What’s inside: • RAG pipelines (Chroma / FAISS) • Custom/opensource LLM integrations • Memory & prompt engineering • Autonomous agents (ReAct style) Built with 2026 best practices to help you get started with production-ready #AI apps. #LLM #LangChain #HuggingFace #Python #MachineLearning #RAG #GenerativeAI https://lnkd.in/gqQ5sZVc
To view or add a comment, sign in
-
I'm pleased to announce the release of FlameIQ v1.0.0 — an open-source, deterministic performance regression engine for Python teams. Performance regressions are rarely caught in code review. They accumulate silently across hundreds of commits — a few milliseconds of latency here, a small throughput drop there — until they become expensive production incidents. FlameIQ brings the same engineering discipline to performance that type checkers bring to correctness: automated, deterministic, and CI-enforced. 🔹 What FlameIQ does: • Compares benchmark results against a stored baseline on every CI run • Enforces per-metric thresholds with direction-aware logic • Applies optional Mann-Whitney U statistical significance testing • Generates self-contained HTML performance reports • Outputs machine-readable JSON for pipeline integration 👉 Install: pip install flameiq-core 👉 Documentation: https://lnkd.in/dGj5YAPv 👉 PyPI: https://lnkd.in/dtTC47Ps 👉 Source: https://lnkd.in/dRdTr-_s 👉 Demo: https://lnkd.in/dpu74wSu I welcome contributions: star, fork and lets build together. #Python #OpenSource #SoftwareEngineering #DevTools #CI #PerformanceEngineering #Benchmarking
To view or add a comment, sign in
-
Most backtests are quietly lying to you - and look-ahead bias is why. Built a vectorized SMA crossover backtesting engine in Python that makes results much closer to real trading outcomes. Every crossover signal is shifted by one day, so a signal on day N only enters on day N+1, no trades based on information from the future. The engine uses pandas.rolling() with boolean masking instead of row-by-row iteration, keeping signal generation at O(n) complexity. On AAPL from 2020 to 2024, a simple SMA 20/50 strategy returned 69.08% vs. 180% buy-and-hold, with a Sharpe of ~0.45 and a max drawdown of ~-18%. Most of this came together during long flights to and from South Africa, which turned into surprisingly productive coding time at 35,000 feet. The architecture is split into four modules: data_loader, strategy, backtest, and visualizer, with yfinance as the data layer and CSV caching to cut redundant API calls. The goal is a modular setup where strategies can be swapped without touching the backtesting core. Repo is open source: https://lnkd.in/dgavp8DG #Quant #AlgoTrading #Python #Backtesting #QuantFinance #OpenSource
To view or add a comment, sign in
-
Python is like that high school ex you run into: you remember the good times, but five minutes in, you're reminded exactly why you moved on. 🐍 After being fully immersed in the TypeScript ecosystem, jumping back into a Python project felt... weird. Going from the safety of strict typing and seamless ESM imports back into the land of manual labor was a wake-up call. Here is the "Welcome Back" package I didn't ask for: The Venv Ritual: Why am I still manually creating and activating virtual environments in 2026? It feels like hand-cranking a car engine just to go to the grocery store. 🛠️ The "Invisible" Packages: That moment when uv list shows the package is there, the interpreter is set correctly, but Python still insists it doesn't exist. Ghosting at its finest. 👻 Manual Everything: Coming from a world where the tooling feels like it has your back, Python's setup feels like it's actively trying to trip you up over a stray .env or a path mismatch. Don't get me wrong, Python is a powerhouse for AI and Data Science, but the developer experience gap is becoming hard to ignore. When you're used to the speed of tools like Bun or the reliability of TS types, those "silly" import errors feel a lot less like a minor bug and a lot more like a tax on your productivity. Has anyone else felt this "syntax shock" lately, or have I just been spoiled by the TS ecosystem? #SoftwareEngineering #Python #TypeScript #WebDevelopment #FullStack #CodingLife
To view or add a comment, sign in
-
-
📖 A Small Lesson That Changed How I Think About Code✨✨ ✍️Imagine two developers 👩💻👨💻 trying to find a number in a list of 1,000,000 items. ⭐Developer A checks each number one by one until they find it. 🔍 ✍️Developer B does something smarter. They keep dividing the list in half, quickly narrowing down where the number could be. ⚡ Both developers solve the problem.✍️ But one takes far longer than the other.😞 This is where Big O Notation comes in. 📊 Big O helps us understand how efficient an algorithm is as the data grows.🤗 For example: 🔹 O(1) – Constant Time ⚡ 🔹 O(log n) – Logarithmic Time 🚀 🔹 O(n) – Linear Time 📈 🔹 O(n²) – Quadratic Time 🐢 As I continue my journey learning Python 🐍 and algorithms, concepts like Big O remind me that great programs are not just built to work — they are built to scale efficiently. 💡 Every line of optimized code brings us closer to building better technology. #Python #Algorithms #BigONotation #TechLearning #Programming #ContinuousLearning
To view or add a comment, sign in
-
-
Back to basics today! 🚀 Sometimes we get so caught up in complex frameworks that we forget the simple nuances of the language itself. I caught myself passing a function's result instead of its reference while coding this morning. It’s these small "Aha!" moments that actually make you a better dev. If you’ve ever stared at a TypeError: 'str' object is not callable for 10 minutes, you know the struggle is real! 😂 Refer the code SS below to understand the difference between calling a function vs. passing it. What’s a "basic" Python concept that still trips you up? 👇 #PythonLearning #IndianTech #CodeLife #Debugging
To view or add a comment, sign in
-
-
😵 Thread-local storage works great... until you move to async. Then the weird stuff starts. Request IDs bleeding between coroutines. Background tasks sharing state. “Random” bugs that disappear under logging. Sound familiar? Async doesn’t care about threads. It cares about execution context. In my latest article I explain: 🔍 Why threading.local() fails under asyncio 🧠 How ContextVars isolate state per coroutine ⚙️ Real examples with async tasks and request-scoped data 👉 https://lnkd.in/d_aVTDtW #python #softwaredevelopment #backend #engineering #asyncio
To view or add a comment, sign in
-
If your goal is to be a Python expert in 2024, then this thread is for you: Here's what we'll cover: • Basic syntax • Advanced topics • Data structures & algos • Web frameworks • Testing With 1-2 hours daily, this will be a 5-6 month journey. Let's go! - Begin with basic syntax, data types, and conditionals. Topics to cover: • Conditionals • Basic syntax • Data types • Variables - Next, complex features. Topics to cover: • Iterators • Lambdas • Decorators • Package managers • Object oriented programming - Next, data structures and algorithms. Topics to cover (there are tons, but here's the most important): • Functions, Builtin Functions • Lists, Tuples, Sets, Dictionaries • Sorting algorithms and recursion - Next, frameworks (both synchronous and asynchronous). Topics to cover (useful for building analytics front ends): • Flask • aiohttp • Django • FastAPI - Finally, testing. Topics to cover: • doctest • unittest • pytest ~~~ The single most *lucrative* way to 2X your career: Python. Most people don't know this, but it's how I made my first $1,000 trading, which kicked off a (profitable) 12+ year career. Here's a free crash course to get started: https://lnkd.in/g6qzjFAD
To view or add a comment, sign in
More from this author
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