Day 4 of #200DaysOfCode! 🚀 After tackling "3Sum" yesterday, I decided to circle back to the problem that started it all for many of us: "Two Sum" (LeetCode 1). While this is often the first problem developers solve, revisiting it with a focus on optimization is always valuable. The Strategy: Space vs. Time Yesterday, for 3Sum, I used sorting and pointers to save space. Today, for Two Sum, I used a Hash Map (Dictionary) to maximize speed. The Logic (One-Pass Hash Map): Instead of using a nested loop to find a pair (which would be a slow O(N^2)), I utilized a dictionary to "remember" the numbers I've seen so far. Iterate through the array. Calculate the complement: diff = target - nums[i]. Check if this diff already exists in our dictionary. If yes, we found our pair! Return the indices immediately. If no, store the current number and its index in the dictionary for future lookups. This approach trades a bit of memory O(N) for a massive gain in speed, bringing the time complexity down to a linear O(N). The Result: My Python solution hit a perfect 0 ms runtime, beating 100.00% of submissions. ⚡ It’s fascinating how different data structures (Hash Maps vs. Pointers) solve similar "Sum" problems in completely different ways. Day 4 down. The foundation is solid. 🧱 Which pattern do you prefer implementing: The "Two Pointer" dance or the "Hash Map" lookup? 👇 #200DaysOfCode #Python #LeetCode #TwoSum #Algorithms #HashMap #DataStructures #ProblemSolving #DeveloperJourney #Optimization
Optimizing Two Sum with Hash Map
More Relevant Posts
-
Day 6 of #200DaysOfCode! 🚀 Sticking with the Linked List theme, today I tackled one of the most essential problems in the data structure's repertoire: "Merge Two Sorted Lists" (LeetCode 21). If yesterday was about math on lists, today was about structure. The Challenge: Given two sorted linked lists, merge them into one single sorted list. Think of it like shuffling two decks of cards that are already sorted, or zipping a zipper. The Logic (The Zipper Technique): I used an iterative approach with Two Pointers (i for list1, j for list2) and a "Dummy Node" to build the result. Comparison: I compare the values at the head of both lists (i.val vs j.val). Selection: I pick the smaller value, add it to my new list, and move that specific pointer forward. The Loop: I keep doing this until one of the lists runs dry. The Cleanup: Once one list is empty, I simply append the remaining elements of the other list to the end (since they are already sorted!). The Result: Another 0 ms runtime, beating 100.00% of Python submissions! ⚡ It is a simple algorithm, but it is the exact same logic used in the "Merge" step of Merge Sort, making it a powerful pattern to master. Day 6 down. The streak is alive and well! 🔥 Do you prefer solving this Iteratively (like I did) or Recursively? The recursive solution is elegant but scary for large lists! 👇 #200DaysOfCode #Python #LeetCode #LinkedList #Algorithms #MergeSort #TwoPointers #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 11/30 | LeetCode Problem: Merge Two Sorted Lists (21) Problem: You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted linked list and return its head. 💡 Approach (Recursive) Since both lists are already sorted: If one list is empty → return the other. Compare the current values of both lists. Attach the smaller node to the result. Recursively merge the remaining nodes. This keeps the final list sorted automatically. ⏱ Complexity Time Complexity: O(n + m) Space Complexity: O(n + m) (due to recursion stack) 🧠 Python Code class Solution: def mergeTwoLists(self, list1, list2): if not list1: return list2 if not list2: return list1 if list1.val < list2.val: list1.next = self.mergeTwoLists(list1.next, list2) return list1 else: list2.next = self.mergeTwoLists(list1, list2.next) return list2 📌 Example Input: list1 = [1,2,4] list2 = [1,3,4] Output: [1,1,2,3,4,4] 🎯 Key Takeaway When working with sorted data structures, compare and attach is a powerful pattern. Also, recursion makes linked list problems elegant and clean. ✅ Accepted 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day11 #Python #LinkedList #Recursion #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7/30 | LeetCode Problem: Two Sum (1) Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume exactly one solution exists. 💡 Approach (Hash Map – Optimal Solution) Instead of checking every pair (which takes O(n²)), we use a dictionary (hash map) to store previously seen numbers. Steps: Iterate through the array. For each number, compute target - current_number. If that value exists in the dictionary → we found the answer. Otherwise, store the needed complement in the dictionary. This reduces the time complexity significantly 🚀 ⏱ Complexity Time Complexity: O(n) Space Complexity: O(n) 🧠 Python Code class Solution: def twoSum(self, nums, target): dis = {} for i in range(len(nums)): if nums[i] in dis: return [dis[nums[i]], i] else: a = target - nums[i] dis[a] = i 📌 Example Input: nums = [2,7,11,15] target = 9 Output: [0,1] 🎯 Key Takeaway Using a hash map can reduce brute-force nested loops into a single-pass solution. Understanding data structures makes problems much easier. ✅ Accepted | 100% runtime 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day7 #Python #HashMap #DataStructures #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 7 of #200DaysOfCode! 🚀 One week down! Today, I took a break from complex data structures to parse some ancient history: "Roman to Integer" (LeetCode 13). 🏛️ At first glance, this seems like simple addition. You just sum up the symbols, right? III = 1 + 1 + 1 = 3 XV = 10 + 5 = 15 But the "Subtraction Rule" throws a wrench in the works. If a smaller symbol appears before a larger one (like IV or IX), it subtracts instead of adds. The Logic (The Lookahead Technique): Instead of complicated string parsing or multiple passes, I used a clean linear scan with a simple rule: Map the Values: I used a Python Dictionary (Hash Map) to store the values ('I': 1, 'V': 5, etc.) for instant lookups. Iterate & Compare: I looped through the string and simply peeked at the next character. * If Current < Next: It means we are in a subtraction case (like the I in IV). I subtract the current value from the total. Otherwise: I simply add the current value. Example: For MCMXCIV (1994): C (100) < M (1000) → Subtract 100 X (10) < C (100) → Subtract 10 I (1) < V (5) → Subtract 1 This logic handles every edge case in a single pass O(N). The result was a flawless 0 ms runtime, beating 100.00% of Python submissions! 7 days in, and the streak is strong. 🧱 Have you tried the reverse problem (Integer to Roman)? I hear the logic is quite different! 👇 #200DaysOfCode #Python #LeetCode #Algorithms #HashMap #Logic #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 8/30 | LeetCode Problem: Merge Sorted Array (88) Problem: You are given two sorted arrays nums1 and nums2, and two integers m and n representing the number of initialized elements in each array. Merge nums2 into nums1 as one sorted array. The final result should be stored inside nums1. 💡 Approach Since nums1 already has enough space at the end (filled with 0s), Steps: Copy elements of nums2 into the empty positions of nums1 Sort the entire nums1 array This ensures the final array remains sorted. ⏱ Complexity Time Complexity: O((m+n) log(m+n)) → due to sorting Space Complexity: O(1) → in-place modification 🧠 Python Code class Solution: def merge(self, nums1, m, nums2, n): for i in range(n): nums1[m + i] = nums2[i] nums1.sort() return nums1 📌 Example Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] 🎯 Key Takeaway Sometimes a straightforward solution works perfectly. Optimization (like using two pointers from the end) can further improve time complexity — but clarity first, then optimization. ✅ Accepted | 100% Runtime 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day8 #Python #Arrays #Sorting #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 9/30 | LeetCode Problem: Best Time to Buy and Sell Stock (121) Problem: You are given an array prices where prices[i] is the price of a stock on day i. Find the maximum profit you can achieve by buying on one day and selling on another future day. If no profit is possible, return 0. 💡 Approach (Greedy – One Pass) Instead of checking every pair of days (O(n²)), we track: min_price → the lowest price seen so far max_profit → the maximum profit found so far For each price: Update min_price if we find a lower value Calculate potential profit (current_price - min_price) Update max_profit if it's larger This allows us to solve the problem in a single traversal. ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 🧠 Python Code class Solution: def maxProfit(self, prices): min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price else: profit = price - min_price if profit > max_profit: max_profit = profit return max_profit 📌 Example Input: prices = [7,1,5,3,6,4] Output: 5 (Buy at 1, Sell at 6) 🎯 Key Takeaway Tracking minimum values while iterating is a powerful pattern in array problems. Greedy + single pass = efficient solution. ✅ Accepted | 91%+ runtime 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day9 #Python #GreedyAlgorithm #Arrays #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 41 of #100DaysofCode Challenge! Today’s focus was on recursion and backtracking patterns: 🔹 Generate Parentheses Solved this using a backtracking approach by building valid combinations incrementally while maintaining two constraints: The number of opening brackets used must not exceed n The number of closing brackets must not exceed the number of opening brackets This ensures only valid sequences are generated without checking invalid ones afterward. Core idea: Use recursion to explore all valid states Add '(' if openings < n Add ')' if closings < openings Key takeaways: ✔ Backtracking with constraint pruning ✔ Recursive state-space exploration ✔ Understanding how valid combinations grow systematically Time Complexity: O(4ⁿ / √n) (related to Catalan numbers) Space Complexity: O(n) for recursion stack Building stronger intuition for recursion and combinatorial problems every day 🚀 📸 Screenshots of solution are attached! #Day41 #DynamicProgramming #BinaryTree #TreeDP #Algorithms #ProblemSolving #Python #Java #CodingMindset #SoftwareEngineering #AdityaVerma #CodingJourney
To view or add a comment, sign in
-
-
Just solved LeetCode 862: Shortest Subarray with Sum at Least K If you've ever been trapped by a sliding window that just won't slide right, this one is for you! 👇 The Brute Force (O(N²)) The most intuitive approach is to calculate the prefix sum of the array, and then use a nested loop to check the sum of every possible subarray, keeping track of the shortest one that is >= K. The problem? The array length can be up to 10⁵. An O(N²) solution will immediately hit a Time Limit Exceeded (TLE). We need O(N). Normally, to find a shortest/longest subarray, we reach for the Sliding Window technique. But there's a catch: The array contains negative numbers. Because of negative numbers, our prefix sum is NOT monotonically increasing. The standard sliding window is completely broken here. To fix this, we need a way to track prefix sums intelligently. We can use a Double-Ended Queue (Deque) to store tuples of (prefix_sum, index) and force it to be strictly increasing (monotonic). Shrinking the window: As we iterate, we check if current_sum - smallest_prefix_sum_in_deque >= K. If it is, we found a valid subarray! We record the length, and throw away that starting index (pop left). Why? Because any future subarray using that start index would only be longer and therefore worse. Maintaining Monotonicity (Pop Right): What if our current_sum dips and is smaller than the most recent prefix sums in our deque? We can keep popping the back of queue as the older greater prefix sums work but make the subarray longer. This approach has a time complexity of O(n) and a space complexity of O(n) as well as in the worst case, the queue may contain n prefix sum where n: number of elements in the array. #LeetCode #Python #Algorithms #DataStructures #SoftwareEngineering #ProblemSolving #CodingInterviews
To view or add a comment, sign in
-
-
🚀 LeetCode 110 – Balanced Binary Tree Today I solved LeetCode #110 – Balanced Binary Tree. 📌 Problem Statement Given a binary tree, determine whether it is height-balanced. A binary tree is considered height-balanced if: For every node, the height difference between its left and right subtree is not more than 1. 🧠 Approach & Technique Used To solve this problem efficiently, I used the Depth-First Search (DFS) approach with a bottom-up recursion strategy. 🔎 Key Idea: Instead of checking height separately for every node (which would increase time complexity), We calculate height while simultaneously verifying balance. If at any node the height difference is greater than 1, we return -1 immediately. This avoids unnecessary recalculations. ⚡ Time & Space Complexity Time Complexity: O(n) → Each node is visited once. Space Complexity: O(h) → Recursive stack space (h = height of tree). 💻 Optimized Python Code class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: def checkHeight(node): if not node: return 0 left = checkHeight(node.left) if left == -1: return -1 right = checkHeight(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return 1 + max(left, right) return checkHeight(root) != -1 🎯 Why This Approach Is Better? ✅ Avoids repeated height calculations ✅ Stops early when imbalance is detected ✅ Clean and optimized recursion ✅ Industry-level approach for tree problems Consistently solving tree problems is strengthening my understanding of recursion and DFS patterns. Looking forward to solving more problems and sharing my journey 🚀 🔥 Hashtags for Better Reach #LeetCode #CodingInterview #DSA #BinaryTree #Recursion #PythonDeveloper #SoftwareEngineer #ProblemSolving #TechCareer #CodingJourney #100DaysOfCode #DataStructures #Algorithms #InterviewPreparation
To view or add a comment, sign in
-
-
Okay I'm long overdue a post, so let's fix that. I built a YouTube video summarizer and actually shipped it — paste in any URL (long-form or Shorts) and it gives you a structured summary: Overview, Key Points, and Conclusion. No watching required. 𝐓𝐡𝐞 𝐬𝐭𝐚𝐜𝐤: Python + FastAPI for the backend Supadata to pull transcripts from YouTube Groq (Llama 3.3 70B) for the AI summaries Hosted on Render Live demo: https://lnkd.in/g8jFDmX3 Source code: https://lnkd.in/gA6Hin-D (hosted on Render's free tier — if it takes a minute to load, just hang tight, it's spinning up) This is also the start of something I'm committing to: 𝐨𝐧𝐞 𝐩𝐫𝐨𝐣𝐞𝐜𝐭 𝐞𝐯𝐞𝐫𝐲 𝐰𝐞𝐞𝐤, shipped and posted publicly. Each one will be open source — if you want to contribute, PRs are open and I review everything that goes in. Follow along, contribute, or just check out the repo. Would love to connect with people building things too. #buildinpublic #python #ai #opensource #softwareengineering
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