🚀 Day 53 of #100DaysOfCode — Making Array Sum Divisible by K Hey everyone! 👋 Today’s challenge focused on a smart math-based optimization problem where the goal was to make the sum of an array divisible by a given number k using the minimum number of operations. 👨💻 What I practiced today: ✅ Understanding modulo (%) operations deeply ✅ Translating a problem into a simple mathematical observation ✅ Optimizing brute-force thinking into an O(n) solution ✅ Writing clean and minimal Python code 📌 Today’s Task: ✔ Given an integer array nums and an integer k ✔ In one operation, decrement any element by 1 ✔ Find the minimum operations required so that sum(nums) is divisible by k 🧠 Key Insight: If the sum of the array is S, then the minimum number of operations required is simply: S % k Because each operation reduces the sum by 1. 💡 Example: Input: nums = [3, 9, 7], k = 5 Sum = 19 → 19 % 5 = 4 Output: 4 ✨ Key Takeaway: Sometimes the best solution isn’t complex logic or loops — it’s recognizing a simple mathematical pattern. Mastering such observations can drastically reduce code complexity and runtime. #100DaysOfCode #Day53 #Python #LeetCode #ProblemSolving #MathInProgramming #CodingJourney #DSA #CleanCode
Day 53 of #100DaysOfCode: Making Array Sum Divisible by K
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
LeetCode Progress | 228. Summary Ranges (Python) Today I solved “Summary Ranges” on LeetCode. Problem: Given a sorted unique integer array nums, return the smallest list of ranges that cover all numbers exactly. A range should be formatted as: -- "a->b" if a != b -- "a" if a == b My approach: I used a two-pointer style tracking method. -- Set start as the beginning of a range -- Iterate through the array and detect when the sequence breaks -- When it breaks, append either a single number or a start->end range -- Update start to begin the next range Optimal approach: The optimal solution follows the same greedy idea (range tracking in one pass). -- Maintain start and extend the current range while consecutive numbers continue -- When the chain breaks or the array ends, output the range and reset start This provides an efficient solution with: -- Time Complexity: O(n) -- Space Complexity: O(1) (excluding output list) What I learned: -- Range problems become easy when you track only the start and detect breakpoints -- Always handle the last element carefully to avoid missing the final range -- Greedy one-pass scanning is often optimal for sorted arrays #leetcode #python #dsa #datastructures #algorithms #coding #programming #problemSolving #softwareengineering #computerscience #interviewprep #codinginterview #100daysofcode #pythonprogramming
To view or add a comment, sign in
-
-
🚀 Day 7/30 | LeetCode Problem: First Unique Character in a String (387) Problem: Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1. Approach: Use a dictionary to count occurrences of each character Traverse the string a second time to find the first character with count 1 Return its index Time Complexity: O(n) → Two passes over the string Space Complexity: O(1) → Dictionary holds at most 26 letters (for lowercase English letters) Python Code: class Solution: def firstUniqChar(self, s): a = {} for i in s: if i in a: a[i] += 1 else: a[i] = 1 for i in range(len(s)): if a[s[i]] == 1: return i return -1 Example: Input: "leetcode" Output: 0 → 'l' is the first unique character Input: "loveleetcode" Output: 2 → 'v' is the first unique character Takeaway: Counting occurrences is a common technique for string problems and can be applied to many scenarios like finding duplicates, frequency analysis, etc. 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day7 #Python #Strings #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
✅ **Day 26 of 100 — List & Dictionary Comprehensions in Action Today’s focus was on writing cleaner, more Pythonic code using list and dictionary comprehensions, including conditional logic inside them. I applied these concepts in the NATO alphabet project, which converts words into their corresponding phonetic alphabet codes. What really stood out was how comprehensions reduce multiple lines of traditional loops into just one expressive line—making the logic clear, concise, and much easier to read. It’s satisfying to see how a little syntax—especially with inline conditions—can dramatically simplify code while boosting readability and performance. #python #100DaysOfCode
To view or add a comment, sign in
-
Recently, I was working on a problem that required dynamically constructing a string. My initial implementation was straightforward and functionally correct. At first glance, it seemed perfectly acceptable. However, upon reviewing the logic more carefully, I revisited how Python handles strings internally. Since strings in Python are immutable, each concatenation inside a loop creates a new string object. This means that with every iteration, memory is reallocated and the existing content is copied over. As input size increases, this results in repeated allocations and copying — leading to unnecessary overhead and potential quadratic time complexity. While this may not be noticeable for small inputs, it becomes increasingly inefficient in production environments where code runs frequently or processes large datasets. To optimize the solution, I refactored the implementation to accumulate values in a list and join them at the end. This approach avoids repeated string creation and achieves linear time complexity, improving both performance and memory efficiency. It was a small refactor, but a meaningful one. Moments like this are a good reminder that understanding language internals — even for simple operations — can significantly impact the quality and efficiency of the code we write. #Python3 #Performance #CleanCode #SoftwareEngineering #Optimization
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
-
-
Day 11/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 136 – Single Number (Easy) 🧠 Approach: Use a hash map to count the frequency of each number. The number that appears exactly once is the answer. Each element appears twice except one, find the unique one. 💻 Solution: class Solution: def singleNumber(self, nums: List[int]) -> int: d={} for i in nums: d[i]=d.get(i,0)+1 for i in d: if d[i]==1: return i ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: When a problem involves frequency or uniqueness, a hash map is often the simplest and most readable solution. #leetcode #dsa #python #problemSolving
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
-
-
🧠 LeetCode Insight — Minimum Window Substring Lately, I’ve been focusing on strengthening my core problem-solving fundamentals, especially patterns that show up repeatedly in real-world engineering problems. One such problem is Minimum Window Substring, which combines: sliding window frequency tracking and careful state management 💡 Core Logic The goal isn’t just to find a valid window — it’s to find the smallest valid window. To do that efficiently: Track required character counts using a frequency map Maintain a dynamic window over the string Expand the window to satisfy constraints Shrink it only when validity is preserved The balance between correctness and optimality is what makes this problem interesting. ✅ Python Implementation: https://lnkd.in/gN-93eB8 🧩 Why This Matters Problems like this test more than syntax — they test: how you manage state how you reason about constraints how you optimize without breaking correctness These are the same skills required when working on scalable backend systems and data pipelines. 🎯 Takeaway The biggest learning for me here was: Sliding window problems aren’t about moving pointers — they’re about knowing exactly when a condition becomes true and when it breaks. Getting that right is what leads to clean, reliable solutions. 👉 Curious how others reason about shrinking windows — what’s your mental model for this pattern? #Python #ProblemSolving #SlidingWindow #DataStructures #SoftwareEngineering #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
The C-Shaped Hole in Package Management In Python Written by $DiligentTECH 💀⚔️ Is it possible for a digital romance to flourish when one partner speaks the language of high-level logic and the other speaks the dialect of raw silicon and compiled C? https://lnkd.in/d8yDPmg8 In today's tutorial we are going discuss the heartbreak and the harmony of the C-Shaped Hole. 1. The Forbidden Liaison: When Python Meets the Metal Imagine Python as a soulful poet ($SlimRich147), creating beautiful, readable verses. But to actually build a house or move a mountain, this poet needs a rugged architect—the C language. Most of Python’s power (like NumPy or TensorFlow) isn't actually written in Python; it’s a C-based engine wrapped in a silk Python glove. https://lnkd.in/dX9-Crhf
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