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
Vishal Balasubramanian’s Post
More Relevant Posts
-
🧠 Python Feature That Makes Attribute Access Clean: operator.attrgetter Think of it as itemgetter for objects 👌 ❌ Common Way users.sort(key=lambda u: u.age) Works… but gets noisy in big codebases 😬 ✅ Pythonic Way from operator import attrgetter users.sort(key=attrgetter("age")) Cleaner. Faster. More readable ✨ 🧒 Simple Explanation Imagine pointing at a toy 🧸 👉 “Sort by age, not the whole toy.” That’s attrgetter. 💡 Why This Is Useful ✔ Cleaner sorting ✔ Faster than lambda ✔ Reads like English ✔ Used in real-world code ⚡ Bonus Trick Get multiple attributes: attrgetter("age", "name")(user) 🐍 Python has tools that remove noise from code. 🐍 attrgetter is one of those features you don’t notice at first… 🐍 until you can’t live without it #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
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
-
In Python, tuple unpacking (also known as iterable unpacking) allows you to take a collection of data and assign it to individual variables in a single, readable line. Instead of doing this: data = (1, 2, 3) a = data[0] You can do this: a, b, c = (1, 2, 3) Why it matters: Readability: It’s immediately clear what the data represents. Efficiency: It reduces boilerplate code. Pythonic: It’s the "intended" way to handle multiple return values from functions. Are you using unpacking in your scripts, or are you still stuck in the index[0] world? Let's discuss below! 👇 #PythonProgramming #CleanCode #DataScience #SoftwareEngineering
To view or add a comment, sign in
-
-
Master Python Nested Loops!🐍 Understanding nested loops is crucial for building more complex programs. Here's a breakdown of how the logic flows, using the code example from theimage: pythonsum = 0 for i in range(1, 4): print("Outer Loop:", i) for j in range(1, 6): # Inner loop runs 5 times for each outer loop iteration (3 total iterations) # We can also track a sum here sum = sum + j # print("Inner Loop:", j) # optional print("Sum:", sum) Use code with caution.💡 The Logic Explained:Outer Loop: for i in range(1, 4) runs 3 times (i = 1, 2, 3). Inner Loop: for j in range(1, 6) runs 5 times for every single iteration of the outer loop (j = 1, 2, 3, 4, 5). Total Iterations:The total number of times the inner code block (e.g., the sum = sum + j line) executes is \(3\times 5=15\) times. Final Output:Outer Loop: 1 Outer Loop: 2 Outer Loop: 3 Sum: 225 (Calculation: the inner loop sums 1+2+3+4+5=15 each time. 15 * 15 = 225) This structure is vital for tasks like working with 2D arrays, matrices, or creating patterns! #Python #Programming #CodingTips #TechEducation #LearnToCode #SoftwareDevelopment # Abhishek kumar # Harsh Chalisgaonkar # SkillCircle™
To view or add a comment, sign in
-
-
🧠 Python Feature That Makes Multiple Dicts Feel Like One: collections.ChainMap 💻 No merging. 💻 No copying. Just smart lookup 👌 ❌ Common Way config = {} config.update(defaults) config.update(env) config.update(user) Messy and order-dependent 😬 ✅ Pythonic Way from collections import ChainMap config = ChainMap(user, env, defaults) Python searches left to right automatically ✨ 🧒 Simple Explanation Imagine checking for a toy 🧸 1️⃣ Check your bag 2️⃣ Check your cupboard 3️⃣ Check the store 💫 Stop as soon as you find it. 💫 That’s ChainMap. 💡 Why This Is Powerful ✔ No data copying ✔ Clean configuration handling ✔ Used in settings & overrides ✔ Interview-friendly concept ⚡ Real Use Case value = config["timeout"] # user → env → defaults 💻 Python doesn’t force you to merge data. 💻 It lets you layer it intelligently 💻 ChainMap is one of those tools you appreciate later. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟭𝟬: 𝗣𝘆𝘁𝗵𝗼𝗻 𝗿𝗮𝗻𝗴𝗲 The range() function is used to generate a sequence of numbers. It is commonly used with loops, especially for loops. Basic syntax: range(start, stop, step) Step can be positive or negative Positive range (counting forward): range(1, 6) # 1, 2, 3, 4, 5 range(0, 10, 2) # 0, 2, 4, 6, 8 Negative range (counting backward): range(5, 0, -1) # 5, 4, 3, 2, 1 range(-1, -6, -1) # -1, -2, -3, -4, -5 Key points to remember: •The stop value is not included •start is optional (default is 0) •step is optional (default is 1) •range() is memory-efficient Common use cases: •Looping a fixed number of times •Generating indexes for lists •Creating number sequences Python range() uses lazy evaluation The range() function does not generate all numbers at once. Instead, it creates numbers only when they are needed. This behavior is called lazy evaluation. #python #programming #range
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
-
-
1) Create a program to check if a given number is even or odd. # Problem Statement: Create a program to check if a given number is even or odd. # Simple Python Program: # get user input num = int(input("Enter a number: ")) # check if number is even or odd if num % 2 == 0: print(num, "is an even number") else: print(num, "is an odd number") # Explanation: # First, we prompt the user to enter a number using the input() function and store it in the variable "num". Then, we use the modulus operator (%) to check if the number is divisible by 2 or not. If the remainder is 0, then the number is even, otherwise it is odd. Finally, we print the appropriate message based on the condition. # Sample Input and Output: # Enter a number: 7 # 7 is an odd number
To view or add a comment, sign in
-
A circular reference happens when two or more objects reference each to other. For example: list A contains a reference to list B and B contains ref back to list A. This creates a cycle. The problem is that Python mainly uses reference counting to delete Objects. An object is removed only when it's reference count becomes 0. In a circular reference, each object still has at least one reference form the other, so their reference count never reaches 0, and they are automatically deleted. This can cause memory to stay used longer than needed. How can python delete this circular reference ? the solution is Python's Garbage collector (GC). It can delect groups of objects that are no longer reachable from the program, even if they reference each other, and it removes them to free memory very simple example : import GC a = [] b = [] a.append(b) b.append(a) del a del b GC.collect() #python #garbageCollector #(GC) #dev #deeplearning #programmation #pythonDev
To view or add a comment, sign in
-
-
🎥 Week 5 | Phase 0 Foundation (Python) | Mini Project video is up. Every LLM test needs data. Prompts. Expected outputs. Thousands of them. This week I built dataset-loader — a tool to load, validate, and save test datasets. What it does: → Load JSON files (single dataset) → Load JSONL files (line-by-line, standard for LLM fine-tuning data) → Validate test case structure → Save results back to file File handling. JSON parsing. pathlib for cleaner paths. The stuff you need when working with real datasets. If you're following along, try building it yourself first. Video's there if you get stuck or want a different perspective. Link in comments. #GenAITesting #LLMTesting #LearnInPublic #Python
To view or add a comment, sign in
Explore related topics
- Leetcode Problem Solving Strategies
- LeetCode Array Problem Solving Techniques
- Approaches to Array Problem Solving for Coding Interviews
- Common Algorithms for Coding Interviews
- Why Use Coding Platforms Like LeetCode for Job Prep
- Strategies for Solving Algorithmic Problems
- Tips for Coding Interview Preparation
- Improving String Repetition Performance in Programming
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