Day 12 of my Python learning journey Today I tried solving a problem that felt like an extension of Two Sum, but it was a bit more tricky. Problem: 3 Sum (using Two Pointers) Given an array, find all unique triplets such that their sum is equal to 0. Example: arr = [-1, 0, 1, 2, -1, -4] Output: [[-1, -1, 2], [-1, 0, 1]] What I learned today: Instead of checking all possible triplets (which is slow), we can: Sort the array first Fix one element Use Two Pointers to find the other two numbers How it works: Fix one number arr[i] Start left from i+1 Start right from the end Check the sum of three numbers • If sum is too small → move left pointer • If sum is too large → move right pointer • If sum is 0 → store the triplet Code I wrote: arr = [-1, 0, 1, 2, -1, -4] arr.sort() result = [] for i in range(len(arr) - 2): if i > 0 and arr[i] == arr[i - 1]: continue left = i + 1 right = len(arr) - 1 while left < right: s = arr[i] + arr[left] + arr[right] if s == 0: result.append([arr[i], arr[left], arr[right]]) while left < right and arr[left] == arr[left + 1]: left += 1 while left < right and arr[right] == arr[right - 1]: right -= 1 left += 1 right -= 1 elif s < 0: left += 1 else: right -= 1 print(result) Problems I faced while coding this: At first I tried using three nested loops, but it became too slow. I did not understand why sorting is necessary. I got duplicate triplets and didn’t know how to remove them. The duplicate skipping logic with while loops confused me a lot. What I finally understood: Sorting helps us use the Two Pointer technique and also makes it easier to avoid duplicates. This approach reduces complexity from O(n³) to O(n²). Time and Space Complexity: Time Complexity: O(n²) → one loop + two pointer traversal Space Complexity: O(1) (excluding the output list) Question: Why do we skip duplicates using: if i > 0 and arr[i] == arr[i - 1]: Today’s realization: Some problems look like small extensions, but the logic becomes much deeper. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
3 Sum Problem Solution with Two Pointers and Sorting
More Relevant Posts
-
Day 13 of my Python learning journey Today I worked on a classic problem that looks simple, but teaches a very powerful idea. Problem: Sort 0s, 1s, and 2s (Dutch National Flag Problem) Given an array containing only 0, 1, and 2, sort it in-place. Example: arr = [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2] What I learned today: Instead of using sorting functions, we can solve this in one pass using pointers. This problem is known as the Dutch National Flag problem. What is Dutch National Flag idea? This concept was given by Edsger Dijkstra. The idea comes from the Dutch flag, which has three colors: Red, White, Blue We map them like this: 0 → Red 1 → White 2 → Blue So the goal is to arrange elements in this order, just like the flag. How the logic works: We divide the array into three parts: Left → all 0s Middle → all 1s Right → all 2s And we maintain three pointers: low → where 0 should go mid → current element high → where 2 should go Code I wrote: arr = [2, 0, 2, 1, 1, 0] low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[high] = arr[high], arr[mid] high -= 1 print(arr) Problems I faced while coding this: At first I tried using sort(), but that defeats the purpose of the problem. I was confused about why we use three pointers instead of two. The condition mid <= high was tricky to understand. I also made mistakes while swapping, which broke the logic. What I finally understood: This algorithm processes each element only once. We don’t need extra space and no nested loops. Time and Space Complexity: Time Complexity: O(n) → single pass through the array Space Complexity: O(1) → in-place sorting Question: Why do we not increase mid when we swap with high? Today’s realization: Some problems are not about coding more, but about thinking in the right structure. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Most people quit learning Python halfway through a tutorial. Not because it's too hard. Because solving fake problems on fake datasets feels pointless. Here's what worked for me: I stopped treating Python like a subject to study and started treating it like a game to beat. Games give you context that tutorials don't. You're not learning "while" loops to pass a quiz. You're learning them to make your robot escape a dungeon or your spaceship dodge asteroids. Same syntax. Totally different motivation. Here are the games that taught me Python without feeling like school: ➡️ CheckiO (checkio.org) Coding challenges disguised as island missions. You unlock levels by solving puzzles with Python. Before you know it, you've mastered loops and conditionals. ➡️ CodinGame (codingame.com) Build AI bots that compete in real-time multiplayer games. Your code controls racing cars, battle droids, and strategy units. Addictive and practical. ➡️ Python Challenge (pythonchallenge.com) A riddle game where every level requires Python to crack. Cryptic, frustrating, and weirdly satisfying when you finally solve it. Teaches problem-solving, not memorization. ➡️ Code Combat (codecombat.com) Fantasy RPG where you write Python to control your character. Move, attack, cast spells — all through code. Works for beginners and advanced players. ➡️ Screeps (screeps.com) MMO strategy game where you program your colony. Automate resource gathering, defense, and expansion. High learning curve, insanely rewarding once it clicks. The reason these work better than tutorials? They give you a reason to care. Tutorials teach syntax in isolation. Games teach syntax in context. You remember "for" loops because you needed them to make your robot move faster. You remember list comprehensions because they helped you filter enemies in battle. Same Python. Better reason to keep going. Shoutout to Karina Samsonova for her SQL game list - she nailed this concept. Dry exercises kill motivation. Games make the syntax stick because the problems feel real, even if they're wrapped in a murder mystery or a space battle. If you've been stuck halfway through a Python tutorial (or avoiding starting at all), try a game instead. Pick one. Play for 30 minutes. You'll be writing code without realizing you're learning. #sql #python #coding
To view or add a comment, sign in
-
Tell your AI that you are beginner when learning Python! I recently asked AI to generate some simple code to reverse two virtual spreadsheet columns called ‘Name’ and ‘Type’. Instead of simply suggesting code in which the column list [‘Name’, ‘Type] is replaced by [‘Type’, ‘Name’], AI suggested a complex indexing trick that looks like [::-1]. Succinct coding, to be sure, but I could not decipher it without additional prompts! In another case, my AI provided some sample code in which a variable was defined after that variable was used! The Horror! When I asked why it made such a fundamental mistake, the AI complimented me on my “good eye” for catching the error and that it did not necessarily provide code in execution order. So, if you are just learning Python, always start your session with a good prompt to set the stage such as the following: "I am a total beginner learning Python. Please follow these rules for ALL Python code you write for me: 1. Write code in execution order. 2. Break every task into small, discrete steps. 3. Use simple, obvious variable names that describe what they contain 4. Add plenty of comments explaining what it happening in plain English 5. Avoid shortcuts, clever one-liners, or condensed syntax that experienced coders use 6. If there are multiple ways to do something, choose the most readable one, not the most efficient one 7. Before showing me code, double-check it runs in the correct order from top to bottom" For more tips, consider my new book "Automate Excel with Python". My publisher @No Starch Press is offering a free review chapter in case you were interested: https://lnkd.in/eS-WAVyV Good luck and good coding! #Excel, #Python, #pandas, #dataframes,#Productivity, #DataAnalysis, #Automation
To view or add a comment, sign in
-
-
⚠️ Python Gotcha — The Mutable Default Argument Trap! This code looks innocent, but behaves surprisingly. Can you guess the output? 🔍 WHAT MOST BEGINNERS EXPECT: print(add_item(1)) → [1] print(add_item(2)) → [2] ⚠️ WHAT ACTUALLY HAPPENS: print(add_item(1)) → [1] print(add_item(2)) → [1, 2] 😲 🔍 WHY THIS HAPPENS: Step 1 → Default arguments are created ONCE when the function is defined Step 2 → Not created each time the function is called Step 3 → 'lst = []' creates a single list that persists Step 4 → Every call shares the SAME list object Step 5 → First call → [1] Step 6 → Second call → [1, 2] Step 7 → Third call → [1, 2, 3] and so on... ✅ HOW TO FIX IT: def add_item(item, lst=None): if lst is None: lst = [] lst.append(item) return lst print(add_item(1)) # [1] print(add_item(2)) # [2] ⚠️ EDGE CASES: Multiple calls → List keeps growing unexpectedly Different arguments → Still shares the same list Function used elsewhere → Unexpected side effects Debugging nightmare → Hard to trace where the list changed 📌 REAL-WORLD APPLICATIONS: 🐛 Debugging → Understanding unexpected behavior 📚 Learning → Teaching Python fundamentals ✅ Code Reviews → Catching this common mistake 🔧 Best Practices → Always use None as the default for mutable types 📝 Interviews → Classic Python interview question 💡 KEY CONCEPTS: • Default arguments → Evaluated once at function definition • Mutable objects → Lists, dictionaries, and sets behave this way • Immutable objects → Integers, strings, and tuples are safe • None as default → Standard workaround pattern • Object reference → Same memory location shared • Side effects → Unexpected modifications 📌 QUICK CHECK: What will this print? def add_item(item, lst=[]): lst.append(item) return lst print(add_item(1)) print(add_item(2)) print(add_item(3)) Answer: [1] → [1, 2] → [1, 2, 3] 👇 Drop your experience — have you ever faced this bug? #Python #PythonGotchas #Coding #Programming #LearnPython #Developer #Tech #Debugging #PythonTips #CommonMistakes #MutableDefaultArguments #Day75
To view or add a comment, sign in
-
-
🚀 Master Machine Learning in Python – From Basics to Advanced Concepts Just explored an amazing set of course notes on Machine Learning in Python, and here are some key takeaways that every aspiring data scientist should know 👇 📌 1. Linear Regression – The Foundation * Understand relationships between variables * Learn concepts like R-squared, OLS, and assumptions * Build predictive models using real-world data 📌 2. Logistic Regression – Classification Made Easy * Predict probabilities instead of exact values * Learn logit functions & model accuracy * Evaluate performance using confusion matrix 📌 3. Clustering – Discover Hidden Patterns * Group data without labels (unsupervised learning) * Learn K-Means clustering & centroid concept * Use techniques like the Elbow Method to find optimal clusters 📌 4. Model Optimization Concepts * Avoid overfitting & underfitting * Use training vs testing data effectively * Understand assumptions like no multicollinearity & homoscedasticity 📌 5. Distance & Similarity Metrics * Euclidean distance for clustering * Helps in grouping similar data points efficiently 💡 One powerful insight: Machine Learning is not just about models — it’s about understanding data, assumptions, and interpretation. These notes are a solid roadmap for anyone starting their ML journey with Python. Pdf credit goes to respective owner. If you want to go beyond theory and build production AI systems, I recently launched a course where we build: * ReAct Agents * Agentic RAG systems * Multi-Agent workflows * Memory-enabled AI agents * Human-in-the-loop applications using LangGraph, one of the most powerful frameworks for building AI agents. 🎓 Course Link https://lnkd.in/dAbXUNwm For the first 100 learners, the course is available at a special discounted price. Follow Pratham Uday Chandratre for more!
To view or add a comment, sign in
-
🚀 Python Practice Series – 5 Questions for Today - Day 3 Keep going. Consistency builds confidence 💪 🔹 Q1 – Find Average of Numbers Question: Find the average of numbers in a list numbers = [10, 20, 30, 40] total = 0 for num in numbers: total += num average = total / len(numbers) print(average) 🔹 Q2 – Count Even and Odd Numbers Question: Count how many even and odd numbers are in a list numbers = [1, 2, 3, 4, 5, 6] even = 0 odd = 0 for num in numbers: if num % 2 == 0: even += 1 else: odd += 1 print("Even:", even) print("Odd:", odd) 🔹 Q3 – Find Common Elements Question: Find common elements between two lists list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] common = [] for num in list1: if num in list2 and num not in common: common.append(num) print(common) 🔹 Q4 – Remove Negative Numbers Question: Remove negative numbers from a list numbers = [-5, 10, -2, 7, 3] positive = [] for num in numbers: if num >= 0: positive.append(num) print(positive) 🔹 Q5 – Find Length of Each Word Question: Given a sentence, find length of each word sentence = "python is easy" words = sentence.split() lengths = [] for word in words: lengths.append(len(word)) print(lengths) 🎯 Summary (Hands-on Learning) Practiced aggregation (sum, average) Learned filtering and counting Worked with multiple lists Handled strings and transformations Improved real problem-solving thinking 👉 Focus: Small problems daily → Strong foundation If anyone is a beginner and learning Python from zero, they can follow the journey here 👇 🔗 https://lnkd.in/gCfExA7C
To view or add a comment, sign in
-
For experienced developers, AI tools like JetBrains AI and PyCharm's code completion features are workflow game-changers. But for Python beginners, are these powerful tools creating a dependency that hinders real skill acquisition? We explore the paradox of features like local code completion and next edit suggestions, and discuss why stepping back from AI assistance might be the most effective way to learn Python. Great learning often comes from identifying – and fixing – mistakes. Read our take and find out how to customize your PyCharm experience for better learning: https://jb.gg/90ime3 #PythonLearning #DeveloperSkills #TechEducation #AIinCoding
To view or add a comment, sign in
-
Recommender Systems using ikpy #machinelearning #datascience #recommendersystems #ikpy LensKit is a set of Python tools for experimenting with and studying recommender systems. It provides support for training, running, and evaluating recommender algorithms in a flexible fashion suitable for research and education. https://lnkd.in/grqEBXKK
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