LeetCode Progress | 258. Add Digits (Python) Today I solved “Add Digits” on LeetCode. Problem: Given an integer num, repeatedly add its digits until the result has only one digit, and return it. My approach: I used an iterative digit-sum process. -- Repeatedly extracted digits using modulo and division -- Summed the digits until the number became a single digit -- Returned the final value Optimal approach (O(1) without loops): This problem follows the mathematical concept of a Digital Root. The result can be found using: -- If num == 0, return 0 -- Otherwise, return 1 + (num - 1) % 9 This avoids iteration entirely and runs in constant time. What I learned: -- Some problems that look iterative have hidden mathematical patterns -- Recognizing number properties (like digital roots) can lead to O(1) solutions -- Always look for a formula when repeated digit operations are involved #leetcode #python #dsa #datastructures #algorithms #coding #programming #problemSolving #softwareengineering #computerscience #interviewprep #codinginterview #100daysofcode #pythonprogramming
Vishal Balasubramanian’s Post
More Relevant Posts
-
Multiple inheritance in Python can be powerful when a class genuinely needs to combine behaviors from different parents (e.g., a string-like object that also counts elements). But the moment those inheritance paths reconnect, you run into the classic diamond problem: the same base class can be reached through multiple routes, so method lookup can become ambiguous if it isn’t handled consistently. Python addresses this with the Method Resolution Order (MRO), computed via C3 linearization. In practice, this gives a predictable search path for attributes and methods: subclasses are checked before base classes, and the order of base classes in the class definition matters. When things are well-formed, you can always inspect the exact lookup chain using ClassName.__mro__ to understand why a specific method implementation is selected. super() fits into this same model: it forwards the call to the next class in the MRO—not simply “the parent.” That makes cooperative multiple inheritance possible (especially with mixins), but it also raises the bar for design discipline. When the goal is clean, safe APIs, the recommended default is often composition over inheritance, keeping mixins small and focused, and using narrower interfaces (e.g., protocols) so classes expose only what they truly need. #Python #SoftwareEngineering #OOP #Programming #CleanCode
To view or add a comment, sign in
-
LeetCode Progress | 242. Valid Anagram (Python) Today I solved “Valid Anagram” on LeetCode. Problem: Given two strings s and t, return True if t is an anagram of s, otherwise return False. My approach: I compared character frequencies between the two strings. -- Created a set of characters from the longer string -- For each character, compared its count in both strings -- If any frequency differed, returned False Optimal approach: A more efficient solution uses frequency counting. -- Use a hash map (dictionary) or fixed-size array (26 characters) -- Increment counts for s and decrement for t -- If all counts are zero, the strings are anagrams This avoids repeated count() calls and improves performance. Follow-up (Unicode characters): -- A dictionary-based frequency counter works well for Unicode -- Arrays are less suitable because the character set is not fixed What I learned: -- Repeated counting inside loops increases time complexity -- Choosing the right data structure can significantly improve efficiency -- Frequency-based problems often have cleaner linear-time solutions #leetcode #python #dsa #datastructures #algorithms #coding #programming #problemSolving #softwareengineering #computerscience #interviewprep #codinginterview #100daysofcode #pythonprogramming
To view or add a comment, sign in
-
-
Headline: Stop writing loops to clean your data. 🛑 One of the most common tasks in Python is handling duplicate entries. While you could write a for-loop with a conditional check, there’s a much faster, more "Pythonic" way to do it: Sets. Sets are unordered collections of unique elements. By casting your list to a set, Python handles the heavy lifting of deduplication instantly. Why use this? ✅ Cleaner, more readable code. ✅ Better performance for large datasets. ✅ Built-in membership testing (O(1) complexity). How are you using Sets in your current workflow? Let’s discuss below! 👇 #PythonProgramming #Pyspiders #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
-
Stop memorising syntax. Start understanding the mechanics. 🧠🐍 Most beginners quit programming not because the code is hard, but because the vocabulary is confusing. They write class or import without knowing why those words exist or what they actually do to the machine. In Day 3 of my Python Fundamentals 2026 series, we stop coding to build a "Mental Map." We break down the 16 Most Critical Python Concepts using real-world analogies that stick: Program vs. Code: Why one is just "Sticky Notes", and the other is a "Full Recipe." The Interpreter: Why Python is like a "Street Food Vendor" (order-by-order) vs. a "Restaurant Kitchen" (Compiler). Indentation: It’s not just style; it’s a strict "Nested To-Do List" that prevents crashes. If you want to move beyond "Hello World" and understand the architecture of the language, this 15-minute guide is for you. 👉 Watch the full breakdown here: [https://lnkd.in/dUHyk-2D] #Python #DataScience #LearningToCode #SoftwareEngineering #Python2026 #TechEducation
To view or add a comment, sign in
-
-
How async/await turns 30 seconds into 3 seconds (without changing the server)? TL;DR: By letting the program handle multiple requests while waiting using async and await! What does AWAIT do? When code hits await, it tells Python: "This will take time, go do something else meanwhile." Python's event loop then switches to another task, keeping the CPU busy instead of idle. What's Actually Happening? -> async def marks a function as asynchronous -> await marks points where the program can pause and switch tasks Note that this works for I/O bound tasks only, CPU bound tasks need multiprocessing. Takeaway: -> async/await is perfect for I/O bound concurrent operations -> 10x performance improvements are common -> The learning curve is worth it for any I/O-heavy application I'm diving deep into Python concurrency. Follow along and share your bottleneck stories in comments! #Python #Concurrency #SoftwareEngineering #BackendDevelopment #Performance
To view or add a comment, sign in
-
-
Python — Week 4: Crawling at Scale with Scrapy 🕷️🐍 This week, I took a big step forward by crawling a website using the Scrapy framework. After manually working with APIs last week, Scrapy felt like a powerful upgrade. Its built-in automation made the entire crawling process much smoother — from handling requests and responses to managing pipelines and data flow. What stood out the most: - Scrapy’s structured approach makes large-scale crawling manageable - Automation reduces boilerplate and keeps the code clean - Handling large datasets becomes far more efficient - Error handling, retries, and concurrency are taken care of gracefully I also followed CodersLegacy tutorials, which were clear, easy to follow, and practical. They made it much easier to understand how Scrapy works under the hood and how to apply it effectively in real-world scenarios. This week reinforced an important lesson: Once the right tools and frameworks are in place, scalability and reliability become much easier to achieve. Looking forward to diving deeper and pushing this further in the coming weeks 🚀 #Python #Scrapy #WebCrawling #Automation #LearningJourney #Backend #DataEngineering
To view or add a comment, sign in
-
🚀 Day 44 of #100DaysOfCode 📌 Problem: 762 – Prime Number of Set Bits in Binary Representation Today I solved an interesting bit manipulation problem on LeetCode that combines binary representation with prime number logic. 🔎 Problem Summary: Given two integers left and right, count how many numbers in that range have a prime number of set bits (1s) in their binary form. 💡 Key Insight: The maximum number of set bits for numbers ≤ 10⁶ is 20. So we only need to check prime numbers up to 20: {2, 3, 5, 7, 11, 13, 17, 19} For each number, count the set bits using: Python Copy code num.bit_count() ✅ Python Solution: Python Copy code class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): if num.bit_count() in primes: count += 1 return count ⏱ Time Complexity: O(n) 🧠 Concepts Used: Bit Manipulation | Prime Numbers | Set Every day I’m getting more comfortable with binary operations and optimization techniques. #LeetCode #Day42 #CodingJourney #Python #ProblemSolving #BitManipulation #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Python Feature That Makes Error Handling Elegant: contextlib.suppress 💫 No noisy try/except. 💫 No empty except: pass. 💫 Just clean intent ❌ Old Way try: os.remove("temp.txt") except FileNotFoundError: pass Works… but feels messy 😬 ✅ Pythonic Way from contextlib import suppress with suppress(FileNotFoundError): os.remove("temp.txt") Readable. Explicit. Clean. 🧒 Simple Explanation Imagine wearing noise-canceling headphones 🎧 You choose which noise to ignore. Python ignores only that error — nothing else. 💡 Why This Is Powerful ✔ Cleaner error handling ✔ Avoids swallowing real bugs ✔ Very expressive code ✔ Used in production-grade code ⚠️ Important Rule Only suppress errors you truly expect (never hide bugs blindly ❌) 💻 Clean code isn’t about removing errors. 💻 It’s about handling them intentionally 🐍✨ 💻 contextlib.suppress is Python being elegant again. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Weekly Challenge 4: Binary Search (Iterative). Why search harder when you can search smarter? Use Binary Search. Imagine looking for a word in a dictionary. Do you read every page from the beginning? No. You open it in the middle and decide: "Left or Right?". That is the essence of Binary Search, and it's the focus of my coding challenge for Week 4. The Implementation: I wrote a Python script (using NumPy) that generates a random environment to test the algorithm. Key Takeaway: While a simple loop (Linear Search) checks elements one by one ($O(n)$), Binary Search cuts the problem in half with every step ($O(\log n)$). Check out the trace in the console output below to see how few attempts it takes to find the target! 👇 📂 Full code on GitHub: https://lnkd.in/ezPaaiDM #Python #BinarySearch #Algorithms #CodingChallenge #DataStructures #Engineering
To view or add a comment, sign in
-
#Learning #Python through Chunks. Lets start journey together (Beginner to Master). Lets code together !! #ABCC - Any Body Can CODE Chunk 8: Comparison & Logical Operators (used in if statements) 🔍 1. Comparison Operators Comparison always results in a Boolean (True or False). 🔗 2. Logical Operators Used to combine conditions. and → both must be True age > 18 and age < 60 or → at least one must be True age < 18 or age > 60 not → flips True/False not is_admin TIY Code (Try It Yourself) x = 10 print(x > 5 and x < 20) # True print(x == 10) # True print(not (x == 10)) # False 🧠 Key takeaways Comparisons → result in Boolean values Logical operators combine or modify conditions Used heavily inside if statements (coming next!)
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