𝐓𝐡𝐞 𝐂𝐚𝐬𝐞 𝐨𝐟 𝐭𝐡𝐞 𝐇𝐢𝐝𝐝𝐞𝐧 𝐋𝐨𝐨𝐩: 𝐏𝐲𝐭𝐡𝐨𝐧 𝐏𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝟏𝟎𝟏 𝐈𝐬 𝐨𝐧𝐞 𝐥𝐨𝐨𝐩 𝐛𝐞𝐭𝐭𝐞𝐫 𝐭𝐡𝐚𝐧 𝐭𝐰𝐨? Not always. When solving the Anagram problem (O(n) time), many developers prefer the Dictionary approach because it looks "cleaner." But let's look under the hood. 𝐎𝐩𝐭𝐢𝐨𝐧 𝐀: The Array Method (Fixed 26 slots) for i in range(len(s)): count[ord(s[i]) - ord('a')] += 1 count[ord(t[i]) - ord('a')] -= 1 for val in count: # Loop #2 if val != 0: return False 𝐎𝐩𝐭𝐢𝐨𝐧 𝐁: The Dictionary Method for i in range(len(s)): countS[s[i]] = 1 + countS.get(s[i], 0) countT[t[i]] = 1 + countT.get(t[i], 0) return countS == countT # Hidden Loop #2 𝐖𝐡𝐲 𝐭𝐡𝐞 𝐀𝐫𝐫𝐚𝐲(𝐎𝐩𝐭𝐢𝐨𝐧 𝟏) 𝐰𝐢𝐧𝐬 𝐨𝐧 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞? 1. The Hidden Loop: That simple == in Option B is also an implicit loop. Python has to iterate through every key and value in both dictionaries to ensure they match. 2. Arrays use direct memory offsets. Dictionaries have to compute a "hash." 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Both are O(n), but "Big O" doesn't tell the whole story. Low-level execution details like hashing overhead and implicit comparisons are where real-world speed is won or lost. #Python #Coding #SoftwareEngineering #Performance #LeetCode
Python Performance: Array vs Dictionary in Anagram Solution
More Relevant Posts
-
Day 17/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 303 – Range Sum Query - Immutable (Easy) 🧠 Approach 1: Brute Force 1. Store the array as it is. 2. For every sumRange(left, right) call, calculate the sum using slicing. 💻 Solution: class NumArray: def __init__(self, nums: List[int]): self.nums=nums def sumRange(self, left: int, right: int) -> int: return sum(self.nums[left:right+1]) ⏱ Time | Space: O(n) | O(1) 🧠 Approach 2: Prefix Sum (Optimized) 1. Precompute prefix sums where each index stores the sum up to that position. 2. Range sum can then be calculated in constant time. 💻 Solution: class NumArray: def __init__(self, nums: List[int]): self.prefix = [0] for num in nums: self.prefix.append(self.prefix[-1] + num) def sumRange(self, left: int, right: int) -> int: return self.prefix[right + 1] - self.prefix[left] ⏱ Time | Space: O(1) | O(n) 📌 Key Takeaway: Prefix Sum is a powerful technique that transforms repeated range sum queries from O(n) to O(1) time, making it ideal for immutable array problems. #leetcode #dsa #python #problemSolving
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟮𝟴/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 162. Find Peak Element 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞, meaning boundary elements can also be peaks. You must write an algorithm that runs in O(log n) time. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: I used a binary search strategy instead of linear scanning. At each step, I compare the middle element with its right neighbor: If nums[mid] > nums[mid+1], a peak must exist on the left side (including mid) If nums[mid] < nums[mid+1], a peak must exist on the right side Based on this comparison, I shrink the search space until start == end, which directly gives the index of a peak element. This works because the array always guarantees the existence of at least one peak due to the -∞ boundary assumption. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(log n) due to binary search • Space Complexity: O(1) since no extra data structures are used 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Peak-finding problems can be solved efficiently using binary search by exploiting local slope properties instead of scanning the entire array. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/g4PPrfri #Day28of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 57 of #100DaysOfCode — Text Formatting & String Manipulation Hey everyone! 👋 Today’s challenge was all about cleaning up data: Capitalizing the first letter of a string while ensuring the rest are lowercase. It’s a common task in web development and data processing to make user input look consistent. 👨💻 What I practiced today: ✅ Case Normalization: Using .lower() to standardize the entire string first. ✅ String Indexing: Accessing the first character with [0] to apply .upper(). ✅ String Concatenation: Merging the transformed first character with the rest of the string using slicing [1:]. 📌 Today’s Task: ✔ Input: A string like "WORLD" or "hello". ✔ Goal: Return a properly formatted string with only the first letter capitalized. ✔ Example: "WORLD" → "World" | "hello" → "Hello". 🧠 Key Insight: While I manually handled the slicing and case conversion today, Python actually has a built-in method called .capitalize() that does exactly this in one step! Understanding the manual way helps me grasp how strings are immutable and how new strings are built in memory. ✨ Key Takeaway: String manipulation is a foundational skill. By breaking a string apart and reassembling it, you learn how to handle more complex text-processing tasks like title casing or custom data parsers in the future. #100DaysOfCode #Day57 #Python #CodingJourney #DSA #Strings #CleanCode #WebDevelopment #DataCleaning #SoftwareEngineer
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟮𝟳/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 394. Decode String 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given an encoded string, return its decoded string. The encoding rule is k[encoded_string], where the encoded string inside the square brackets is repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, and the original data does not contain any digits. Digits are used only for repeat counts. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: A recursive depth-first approach with a global index is used to traverse the string. While iterating through the characters, build the repeat count when a digit is encountered. When an opening bracket [ appears, recursively decode the substring inside it. Once the closing bracket ] is reached, the decoded inner string is repeated k times and appended to the current result. This recursive structure naturally handles nested encoded patterns while maintaining a single traversal over the string. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), where n is the length of the string • Space Complexity: O(n), due to recursion depth and string construction 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Recursive parsing with a shared index is a clean and effective alternative to stacks when solving problems involving nested string decoding. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/giV4yAAG #Day27of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 77 of #100DaysOfCode — Find the Second Largest Digit Hey everyone! 👋 Today's challenge is "Second Largest Digit in a String" — a great problem for practicing digit extraction, comparison logic, and edge-case handling. We’ll search through a mixed string of letters and numbers to find the second largest digit, or return -1 if it doesn’t exist. 👨💻 What l practiced today: ✅ String Traversal: Looping through each character and identifying digits. ✅ Digit Comparison: Keeping track of the largest and second-largest digits efficiently. ✅ Edge Cases: Handling cases with no digits, only one digit, or duplicate digits. 📌 Today’s Task: ✔ Given an alphanumeric string s. ✔ Return the second largest numerical digit that appears in s. ✔ Return -1 if it doesn’t exist. Example: Input: s = "dfa12321afd" Digits: [1, 2, 3] Second largest: 2 → Output: 2 🧠 Key Insight: You can solve this by scanning the string once, tracking the largest and second largest digits. Remember to skip duplicates and handle cases where all digits are the same. #100DaysOfCode #Day77 #Python #LeetCode #DSA #StringManipulation #DigitExtraction #EdgeCases #AlgorithmPractice #LogicBuilding
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟭𝟲: 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝘆 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻 🐍 🔹 A dictionary is a built-in, mutable data structure that stores data in key–value pairs 🔹 Key–value pairs are separated by commas and enclosed in curly braces {} 🔹 Data is stored as key : value 🔹 Keys must be unique 🔹 Dictionaries are ordered (from Python 3.7+) 𝗔𝗰𝗰𝗲𝘀𝘀𝗶𝗻𝗴 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝘆 𝗜𝘁𝗲𝗺𝘀 🔹 Two main ways to access values: 1️⃣Using keys → dict_name[key] (raises error if key not found) 2️⃣Using get() → dict_name.get(key) (returns None if key not found) 🔹 Access all values using → dict_name.values() 𝗔𝗱𝗱𝗶𝗻𝗴 & 𝗠𝗼𝗱𝗶𝗳𝘆𝗶𝗻𝗴 𝗜𝘁𝗲𝗺𝘀 ➕Using assignment operator → dict_name[key] = value ➕ Using update() → adds or updates key-value pairs 𝗥𝗲𝗺𝗼𝘃𝗶𝗻𝗴 𝗜𝘁𝗲𝗺𝘀 ❌ del dict_name[key] → removes a specific key ❌ pop(key) → removes key and returns its value ❌ popitem() → removes the last inserted key-value pair ❌ clear() → removes all items #Python #Dictionary #LearningPython #LearningInPublic #Consistency
To view or add a comment, sign in
-
DSA — LeetCode #760: Anagram Mapping I worked on a classic Data Structures & Algorithms problem and added it to my LeetCode journey. Problem Statement Given two integer arrays s and t, where t is an anagram of s, return an array mapping such that: mapping[i] is the index in t where the value s[i] appears. If a value occurs multiple times, any valid index can be returned. Approach Use a hash map to store indices of elements in array t. Traverse t and map each value to its index (or list of indices). Iterate through array s and fetch the corresponding index from the map. Build the result array using these indices. Example Input: s = [16, 5, 12, 10] t = [5, 10, 12, 16] Output: [3, 0, 2, 1] Complexity ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) #DSA #LeetCode #ProblemSolving #Python #CodingInterview #Algorithms #DataStructures #HashMap #Anagram #CodingPractice #TechJourney #SoftwareEngineering #InterviewPrep #LearnToCode
To view or add a comment, sign in
-
-
One concept I understand better now is List Comprehensions. Sometimes I felt like my python scripts were getting cluttered with repetitive for loops and .append() calls. I used to think list comprehensions were just a shorthand trick, but they are actually a more efficient way to handle data transformation. It’s the difference between writing a paragraph and writing a perfectly concise sentence. The syntax used to look intimidating, but here is how it finally clicked for me: new_list = [expression for item in iterable if condition] The Expression: What do you want to keep? (e.g., x or x**2) The Loop: Where is it coming from? (e.g., for x in my_list) The Filter: Do you want all of them or just some? (e.g., if x > 10) Why I’m using it from now on: Readability: Once you know the syntax, you can read the logic in a single line. Speed: It’s technically faster than a standard loop. Less Room for Error: No need to initialize empty lists or manage counters. Small shifts in syntax lead to big jumps in code quality. NativesPlug @locus.ioe #LOCUS2026 #NativesPlug #LearningChallenge #15DayChallenge #NepalTech #LearnAndWin #PythonTips
To view or add a comment, sign in
-
I cleaned up local scripts that I had been repeatedly using and I'm releasing it as a new python package named `RetroFlow`. It makes beautiful, minimalist ASCII flow charts from simple strings like the following. It supports title banners, complex cycles, and more. simple_diagram = """ A -> B B -> C C -> D C -> E E -> A """ Beyond their cool, retro look straight out of the "golden age of computing" era, they have a real advantage now that agentic software engineering has become the norm: These ASCII, pure text diagrams can happily live inline with: PRs and other technical settings. Yes, agents can read images, but in my experience they more easily internalize these tiny representations (vs an image or full deck). Yes, you could just have agents read from things like the code block above but this is a visual format both people and agents can easily understand. Let me know what you think! Blog post: https://lnkd.in/euPzKegk GitHub: https://lnkd.in/ekw-RAEg PyPi: https://lnkd.in/etPvPvVU #Python #AI #DataVisualization #OpenSource
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟴/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 334. Increasing Triplet Subsequence 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given an integer array nums, return true if there exists a triplet of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such triplet exists, return false. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Initialized two variables a and b with the maximum possible integer value. Iterated through the array and applied the following logic: • If the current number is less than or equal to a, update a (smallest value so far). • Else if the current number is less than or equal to b, update b (second smallest value). • Else, the current number is greater than both a and b, which confirms the existence of an increasing triplet, so return true. If the loop completes without finding such a condition, return false. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), due to single array traversal • Space Complexity: O(1), since only constant extra space is utilised. 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Greedy tracking of the smallest and second smallest elements enables detecting an increasing triplet efficiently in linear time and constant space. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gGaGM5ps #Day8of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
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
Interesting work Umesh Yadav