🚀 Day 55 of #100DaysOfCode — Counting Characters & Pythonic Efficiency Hey everyone! 👋 Today was all about String Manipulation. The task was to write a function that returns the total number of characters in a given string. While it’s a simple concept, it’s a great exercise to visualize how data is traversed in memory. 👨💻 What I practiced today: ✅ String Iteration: Using a for loop to step through a string character by character. ✅ Counter Logic: Manually incrementing a variable to track the sequence length. ✅ Edge Case Handling: Ensuring the function correctly returns 0 for an empty string "". 📌 Today’s Task: ✔ Given a string s. ✔ Traverse the string and count every character. ✔ Return the final count. 🧠 Key Insight: In my solution today, I manually built a counter (O(n) time). However, in Python, the len() function is the most efficient way to do this. Unlike a manual loop, len() is O(1) (constant time) because Python stores the length of the string as an attribute in memory! ✨ Key Takeaway: Learning the manual logic behind basic tasks is essential for mastering algorithms, but knowing when to use built-in functions like len() is what makes your code professional and performant. #100DaysOfCode #Day55 #Python #CodingJourney #DSA #Strings #CleanCode #LogicBuilding #SoftwareEngineering #Programming
Pradumya Gupta’s Post
More Relevant Posts
-
🚀 Day 6/30 | LeetCode Problem: Move Zeroes (283) Problem: Given an array nums, move all 0s to the end of the array while maintaining the relative order of non-zero elements. The operation must be done in-place. Approach: Traverse the array once Store all non-zero elements in one list Store all zero elements in another list Combine both lists and update the original array This approach keeps the order intact and is easy to understand. Time Complexity: O(n) Space Complexity: O(n) Python Code: class Solution(object): def moveZeroes(self, nums): a = [] b = [] for i in nums: if i == 0: a.append(i) else: b.append(i) nums[:] = b + a Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Takeaway: Maintaining order while modifying arrays is a common requirement in real-world problems. 📌 Accepted ✅ | All test cases passed 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day6 #Python #Arrays #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 4/30 | LeetCode Problem: Running Sum of 1D Array (1480) Problem: Given an array nums, return the running sum, where each element at index i is the sum of elements from index 0 to i. Approach: Initialize a variable to store the cumulative sum Traverse the array one by one Add each element to the cumulative sum Store the result in a new list This is a simple single-pass solution. Time Complexity: O(n) Space Complexity: O(n) Python Code: class Solution: def runningSum(self, nums): a = 0 b = [] for i in nums: a = a + i b.append(a) return b Example: Input: [1, 2, 3, 4] Output: [1, 3, 6, 10] Takeaway: Running sum is a basic form of prefix sum, which is very useful in many array problems. 📌 Accepted ✅ | All test cases passed 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day4 #Python #DSA #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
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 11 of 150: Handling Errors in Python Moving past the "happy path" today to focus on what happens when things break. Understanding how to handle exceptions properly is a huge part of moving from writing scripts to building production-ready code. What I worked on: • The Try-Except Block: Not just catching everything with a generic except, but targeting specific errors like ValueError or KeyError so the code doesn't fail silently. • Else & Finally: Using else for logic that only runs on success and finally for the "must-run" cleanup, like closing a file or a database connection. • Raising Errors: Learning when it's better to intentionally raise an exception to stop bad data from moving further into the system. • Custom Exceptions: Writing my own error classes to make debugging easier and more specific to the project. It’s less about making the code work and more about making it resilient. 139 days to go. #Python #SoftwareEngineering #ErrorHandling #150DaysOfCode #InterviewPrep
To view or add a comment, sign in
-
Day 7 of 365 Days of code 🤌 Qn 1):Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Explanation: Use two different pointers, one is going to be a slow pointer and another one will be a fast pointer that moves twice the number of nodes of the slow pointer in a single iteration. If both the pointers meet at a same node, then the linked list consists of a cycle. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
To view or add a comment, sign in
-
-
#Day02 of 50 Days of Learning hashtag#Python through hashtag#Automation On Day 02, I moved from basics to a real-world automation task 📸 Today, I learned how to automatically resize multiple images using Python and the Pillow (PIL) library. What I covered: • What Pillow (PIL) is and why it’s needed • How to install external libraries using pip • Looping through folders to process files automatically • Resizing images while maintaining aspect ratio • Using Python for bulk image automation This script can resize hundreds of images in seconds — useful for: ✔ Websites ✔ Applications ✔ Automation workflows Read the full blog here 👇 https://lnkd.in/gSFXiAjW
To view or add a comment, sign in
-
#100DaysOfchallenge-Day-11 – Strengthening Python Foundations 🐍 Today’s focus was on writing flexible and reusable code. 📌 Topics covered: • Functions with multiple arguments • Default parameters • *args for variable-length arguments • Understanding common runtime & syntax errors Learning how Python behaves internally makes debugging easier and code cleaner. 🔗 https:https://lnkd.in/gV9XFn5X Step by step. Building strong basics. #PythonProgramming #100DaysOfCode #Day11 #CodingJourney #Codegnan
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
-
-
🚀 Want more “Pythonic” code in 5 minutes? These little tricks are not magic. They are tiny shortcuts that make your code cleaner, faster to read and easier to maintain If you write Python daily, keep this cheat sheet nearby ⏱️ 1: List comprehensions — build lists fast, clean, and Pythonic [...] 2: zip() — pair lists by index, no manual loops zip(names, ages) 🔗 3: Unpacking — swap and split values in one step a, b = b, a 🔁 4: *args and **kwargs — flexible functions that accept any inputs def f(*args, 5: **kwargs) 🧩 enumerate() — loop with index without extra counters enumerate(items) 🧠 #Python #Programming #CodingTips #Developer #CleanCode #LearnPython #DevCommunity
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
-
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