Day 9: Mastering the Two-Sum Strategy 🎯 💡 How I solved it: Instead of a slow O(n^2) nested loop to find pairs, I used a One-Pass Hash Map to achieve a lightning-fast O(n) solution. Target Calculation: For every number n, I calculated the diff (target - n) needed to complete the pair. Instant Lookup: I checked if this diff already existed in my prev_map. If it did, I immediately returned the indices. Dynamic Mapping: If the complement wasn't found, I stored the current number and its index {val: index} in the map to be used for future lookups. The Single Pass: This allowed me to find the answer in just one trip through the array. 🧠 Key Takeaway: Efficiency First: Trading a tiny bit of memory O(n) space for a massive gain in speed O(n) time is the hallmark of an optimized algorithm. Complement Logic: Learned that searching for a "pair" is really just searching for a "complement." Dictionary Power: This project reinforced how Python’s dictionary lookups are O(1) on average, making them the ultimate tool for reducing time complexity. One step closer to mastering Data Structures and Algorithms! 💻🔥 The logic is getting sharper every day! 📈🤝 #100DaysOfCode #DSA #Python #TwoSum #ProblemSolving #StriverA2ZSheet #CodingJourney
Two-Sum Strategy: O(n) Solution with Hash Map
More Relevant Posts
-
Topic 5/100 🚀 🧠 Topic 5 — Iterators Ever wondered how a for loop actually works behind the scenes? 🤔 This is the concept powering it. 👉 What is it? Iterators are objects that allow you to traverse through data step-by-step using __iter__() and __next__() methods. 👉 Use Case: Used in real-world applications for: Custom data pipelines Streaming data Building your own iterable objects 👉 Why it’s Helpful: Gives full control over iteration Enables custom looping logic Foundation for generators 💻 Example: class Counter: def __init__(self, max): self.max = max self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.max: self.current += 1 return self.current raise StopIteration for num in Counter(3): print(num) 🧠 What’s happening here? We created a custom object that behaves like a loop by controlling how values are returned one by one. ⚡ Pro Tip: If you understand iterators, you’ll unlock how Python handles loops internally. 💬 Follow this series for more Topics #Python #BackendDevelopment #100TopicOfCode #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
**IMPORTANT: The website techtonique dot net [https://lnkd.in/eSRESGyy) is down until further notice.** [https://lnkd.in/eSRESGyy) contained an language-agnostic API for machine learning tasks (classification, regression, survival analysis, forecasting etc.). As a result, do not buy the Gumroad tutorial then. You can still use the R and Python Github packages [https://lnkd.in/eXN_dSKW) locally. PS: It's not an April's fool joke.
To view or add a comment, sign in
-
Topic 3/100 🚀 🧠 Topic 3 — Context Managers Ever forgotten to close a file or database connection? 😅 That’s where this concept saves you. 👉 What is it? Context Managers allow you to manage resources automatically using the with statement. 👉 Use Case: Used in real-world applications for: File handling Database connections Managing locks in concurrent systems 👉 Why it’s Helpful: Prevents memory leaks Automatically cleans up resources Makes code cleaner and safer 💻 Example: with open("file.txt", "w") as f: f.write("Hello, World!") 🧠 What’s happening here? Python automatically opens the file and ensures it gets closed after the block executes — even if an error occurs. ⚡ Pro Tip: Always use context managers when working with external resources — it’s a best practice in production code. 💬 Follow this series for more Topics #Python #BackendDevelopment #100TopicOfCode #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
💻 Solved a great problem today: Count Increasing Subarrays 🚀 Given an array, the task was to count all strictly increasing subarrays of size ≥ 2. 🔍 Approach I used: Broke the array into continuous increasing segments For each segment of length k, calculated subarrays using the formula: 👉 k(k-1)/2 Summed all results to get the final answer ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 💡 This problem helped me understand how breaking a problem into patterns can simplify complex logic. Here’s my Python solution 👇 class Solution: def countIncreasing(self, arr): list2 = [] list2.append(arr[0]) list3 = [] for i in range(1, len(arr)): if arr[i-1] < arr[i] and arr[i] > 2: list2.append(arr[i]) else: list3.append(list2) list2 = [] list2.append(arr[i]) list3.append(list2) ans = 0 for i in list3: if len(i) > 1: ans += (len(i) * (len(i) - 1)) // 2 return ans 🔥 Always learning, always improving. #python #dsa #coding #problemSolving #programming #developers #learning
To view or add a comment, sign in
-
-
🚀 Solved a great problem today: “Consecutive 1’s Not Allowed” At first glance, it looked like a simple binary string problem… but it quickly turned into a lesson in pattern recognition and dynamic thinking. 📌 What the problem was about: Count all binary strings of length n such that no two 1’s are consecutive. 💡 What I learned: Instead of brute forcing all combinations (which would be exponential), the key was to observe a pattern: If a string ends with 0 → we can add 0 or 1 If it ends with 1 → we can only add 0 This leads to a recurrence: 👉 dp[n] = dp[n-1] + dp[n-2] Which is basically the Fibonacci pattern in disguise. 🧠 Big takeaway: Many problems are not about coding harder… they’re about seeing the hidden pattern behind the problem. This was a reminder that: Brute force is rarely the answer Thinking in terms of state transitions is powerful Optimization often comes from observation, not syntax 📷 Sharing my solution screenshot below 👇 #DataStructures #DynamicProgramming #ProblemSolving #Python #LearningInPublic #DataAnalyticsJourney
To view or add a comment, sign in
-
-
🚀 Solved a LeetCode Problem – Running Sum (Prefix Sum Concept) Today I solved a problem based on the Running Sum / Prefix Sum concept. 🔍 Problem Statement: Given an array, compute a new array where each element at index i represents the sum of all elements from index 0 to i. 💡 My Approach: Instead of recalculating the sum for every index (which would be inefficient), I used an incremental approach: I initialized a result list with the first element. Then, I iterated through the array starting from index 1. At each step, I updated the current element by adding the previous cumulative sum: 👉 Current element = Current value + Previous running sum I stored each updated value in the result list. This way, I reused previously computed results instead of recomputing sums again and again. ⚡ Why this is efficient? Each element is processed only once. No nested loops are used. Avoids redundant calculations. ⏱️ Complexity Analysis: Time Complexity: O(n) → Single pass through the array Space Complexity: O(n) → Extra list used to store results 📌 Key Learning: This problem helped me understand the importance of Prefix Sum technique, which is widely used in problems involving range sums, subarrays, and optimizations. 💻 Code: class Solution: def runningSum(self, nums: List[int]) -> List[int]: res=[] res.append(nums[0]) for i in range(1,len(nums)): nums[i]=nums[i]+nums[i-1] res.append(nums[i]) return res #100DaysOfCode #Python #DSA #CodingJourney #PrefixSum #ProblemSolving
To view or add a comment, sign in
-
-
I had the chance to delve into the Noise2Void codebase from zero and I must say I absolutely adored the way it was organized. The project has the workflow decoupled into very specific parts such as data handling, masking, and model training, thus making it easier for the reader to grasp the contents of the code. What I found to be the most remarkable part is the trick that the code employs through the use of custom functions and training logic to hide pixels and let the network predict from surrounding context. This is an excellent project that exhibits how well clean Python structure and TensorFlow-based modeling can work together in a smart self-supervised learning environment. Another thing I found useful was the codebase with its logic being modular, which gives the pipeline a practical and well-engineered feeling instead of being too complicated. Repo: https://lnkd.in/eF7nZXxX
To view or add a comment, sign in
-
-
I used to think tuples were just “lists with stricter rules”… but today showed me they have their own vibe. 🐍 Day 06 of my #30DaysOfPython journey was all about tuples, and this topic made one thing really clear: sometimes the best data structure is the one that stays put. A tuple is an ordered and unchangeable collection of different data types, created using round brackets (). Today I explored: 1. Creating tuples with tuple() 2. Accessing items using positive and negative indexing 3. Slicing tuples with positive and negative indexes 4. Checking whether an item exists using in 5. Counting items with count() 6. Finding item positions with index() 7. Joining tuples using + operator 8. Converting tuples to lists with list() 9. Deleting the whole tuple using del What stood out to me today was how tuples are built for stability. They are not meant to be edited over and over again — and that actually makes them really useful when you want data to stay consistent. One more day, one more topic, one more layer of Python making sense. Github Link - https://lnkd.in/gHwugKTU #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
🚀 Day 57 of #100DaysOfCode Solved LeetCode 290 – Word Pattern today! 🧠 Problem Insight: We are given a pattern and a sentence. The goal is to check whether there exists a one-to-one mapping (bijection) between characters in the pattern and words in the sentence 💡 Key Learning: One character → one unique word One word → one unique character No duplicates allowed in mapping (both directions) ⚡ Approach I Used: Split sentence into words Use two hash maps: Character → Word Word → Character Validate mapping consistency while iterating 🎯 Why this problem matters: This is a classic example of: Hashing Data consistency checks Bidirectional mapping logic (very important in interviews) 📊 Performance: ✅ Runtime: 0 ms (Beats 100%) ✅ Memory: Optimized 🔥 Takeaway: Always think in two directions when mapping relationships — it avoids hidden edge cases. #DSA #LeetCode #CodingJourney #Python #ProblemSolving #TechGrowth #Consistency #100DaysChallenge
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