Day 3 of #200DaysOfCode! 🚀 Today, I leveled up from finding pairs to finding triplets with the classic "3Sum" problem (LeetCode 15). The goal is to find all unique triplets in an array that sum up to zero. The naive approach (three nested loops) is a painfully slow O(N^3). To solve this efficiently, I had to combine sorting with the Two Pointer technique. My O(N^2) Approach: Sort First: I started by sorting the array. This is crucial because it allows us to use pointers effectively and easily handle duplicates. Fix One, Solve Two: I iterated through the array with a fixed pointer i. For each number, the problem reduces to finding two other numbers that sum to -nums[i]. The "Two Pointer" Sweep: I placed a left pointer at i+1 and a right pointer at the end. If the sum is too small, move left forward. If the sum is too big, move right backward. The Tricky Part (Duplicates): The real challenge in 3Sum is avoiding duplicate triplets (e.g., [-1, -1, 2] appearing twice). As you can see in my code, I implemented while loops to skip over identical elements for both the fixed number and the pointers. It’s satisfying to see how sorting the data upfront makes a complex problem much more manageable. 3 days down! Consistency is building. 🧱 Has anyone tried extending this logic to "4Sum"? Does the recursion get messy? 👇 #200DaysOfCode #Python #LeetCode #Algorithms #TwoPointers #3Sum #ProblemSolving #CodingChallenge #DeveloperJourney
3Sum Problem Solution with Two Pointer Technique
More Relevant Posts
-
LeetCode Problem 160: "Intersection of two Linked Lists": Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. Approach: Use two pointers technique, maintain one pointer at list A and another at list B, at each iteration check whether pointers point to the same node, if yes then return that node. If pointer A reaches end update it to point to the head of list B and if pointer B reaches end update it to point to the head of list A. In this way each of the pointers traverses both of the lists. Time complexity: O(m+n) Space Complexity: O(1) #LeetCode #LinkedLists #Python #CompetitiveProgramming #ProblemSolving #Algorithms #DataStructures
To view or add a comment, sign in
-
-
✅ Day 64 of 100 Days LeetCode Challenge Problem: 🔹 #1784 – Check if Binary String Has at Most One Segment of Ones 🔗 https://lnkd.in/gpJYed9J Learning Journey: 🔹 Today’s problem focused on determining whether a binary string contains only one contiguous segment of '1's. 🔹 Since the string has no leading zeros, the first character is always '1'. 🔹 If a '1' appears again after a '0', it indicates the start of a second segment. 🔹 A single pass through the string is enough to detect this pattern. Concepts Used: 🔹 String Traversal 🔹 Pattern Detection 🔹 Conditional Logic Key Insight: 🔹 The pattern "01" followed by another '1' reveals multiple segments of ones. 🔹 Detecting this transition allows us to solve the problem efficiently. Complexity: 🔹 Time: O(n) 🔹 Space: O(1) 💬 What’s your favorite trick for solving binary string problems? #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
Just launched my Simple Calculator powered by Groq API and deployed on Hugging Face Spaces! #nter any math expression, and the LLM calculates it instantly. Built with Python and Gradio in just two files (app.py & requirements.txt). Hugging Face deployment makes it easy to share and access online. This project is a fun example of combining AI APIs with simple web interfaces. It also shows how easy it is to deploy projects for anyone to try. Check it out here: https://lnkd.in/dRuV2wU7 #AI #GroqAPI #Python #HuggingFace #Gradio #MachineLearning #DeveloperLife
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
-
-
Weekly challenge 5: Recursion To understand recursion, you must first understand recursion. For Week 5 of my algorithm challenge, I decided to tackle a concept that trips up many beginners: Recursive Functions, using the classic Factorial problem. What is Recursion? Instead of using a standard `for` or `while` loop, a recursive function calls **itself** to solve a smaller piece of the problem. It keeps digging deeper until it hits a "Base Case" (the bottom), and then it passes the answers back up the chain. Think of it like a set of Russian nesting dolls. The Trade-off:** > While recursive code is extremely clean and mathematical, it uses more memory. Every time the function calls itself, it adds a new layer to the computer's **Call Stack**. If you forget your Base Case, your program crashes with a "Stack Overflow"! > > I added a visual trace to my Python script so you can literally see the Call Stack growing and shrinking in the console. Check the full code and console output on GitHub: https://lnkd.in/es5TzCUg #Python #Recursion #Algorithms #CodingChallenge #SoftwareEngineering #DataScience
To view or add a comment, sign in
-
𝗜 𝗳𝗼𝘂𝗻𝗱 𝗮 𝟰𝟰× 𝘀𝗽𝗲𝗲𝗱 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗶𝗻 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝘀𝘂𝗺() 𝗼𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻 🚀 I benchmarked three ways of summing 100,000 numbers: • Manual for loop → ~11.4 ms • Built-in 𝘀𝘂𝗺() → ~8.27 ms • 𝗻𝗽.𝘀𝘂𝗺() → ~0.259 ms 𝗡𝘂𝗺𝗣𝘆 𝘄𝗮𝘀 ~𝟰𝟰× 𝗳𝗮𝘀𝘁𝗲𝗿 𝘁𝗵𝗮𝗻 𝗮 𝗣𝘆𝘁𝗵𝗼𝗻 𝗹𝗼𝗼𝗽 ⚡ The real insight isn’t that “NumPy is faster.” It’s about execution layers. A Python loop runs inside the interpreter with dynamic checks every iteration. 𝘀𝘂𝗺() shifts the work into C. 𝗻𝗽.𝘀𝘂𝗺() operates on contiguous memory using optimized low-level code, avoiding Python-level iteration entirely. Same computation. Different execution layer. Massive performance gap. #Python #NumPy #DataScience #LearningInPublic
To view or add a comment, sign in
-
-
LeetCode Problem 1758: "Minimum changes to make alternating binary string": You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating. Approach: Here are two possibilities, first do not make change in the 1st character and apply rules following it, second consider step of changing the very first character and apply rules following it. The below implementation in Python works on this principle only, simple and straightforward. #Python #LeetCode #Strings #OptimalSolution #CompetitiveProgramming #DataStructures #Algorithms #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode Problem 1545: "Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0)." Approach: Initialize an array with a single element '0' which serves as the string1 then iteratively calculate the consecutive strings and store them in the array. Finally, form the final string using the join() function and return the kth character of the string. #Python #LeetCode #String #ProblemSolving #CompetitiveProgramming #DataStructures #Algorithm
To view or add a comment, sign in
-
-
🚀 Day 41 / 200 Days of Code Solved the “Majority Element” problem on LeetCode today! 🔹 Problem: Find the element that appears more than ⌊n/2⌋ times in an array. 🔹 Constraint: Majority element is guaranteed to exist. 🔹 Approach Used: Python built-in optimization (max(set(nums), key=nums.count)) 🔹 Status: ✅ Accepted 🔹 Runtime: 0 ms 🔹 Memory: 21.07 MB (Beats 84.28%) While a simple built-in solution works, I also explored the Boyer–Moore Voting Algorithm, which solves it in O(n) time and O(1) space — a powerful technique frequently asked in interviews. 💡 Key Learning: Efficient problem-solving isn’t just about passing test cases — it’s about understanding optimized approaches and improving algorithmic thinking. Consistency > Motivation. One problem a day. Steady progress toward mastery. #Day41 #200DaysOfCode #LeetCode #Python #DataStructures #Algorithms #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
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
-
Explore related topics
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