Leetcode Practice - 15. 3Sum The problem is solved using JAVA. Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
3Sum Problem Solution in Java
More Relevant Posts
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Same Tree 💻 Language: Java 🔹 Approach: To solve this problem, I used Recursion to compare both binary trees node by node. • If both nodes are null → return true • If one node is null and the other is not → return false • If node values are different → return false • Recursively compare left subtrees • Recursively compare right subtrees • If both left and right comparisons return true → both trees are identical This approach works because each subtree is itself a smaller version of the same problem, making recursion a natural fit. ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(h) (where h = height of tree, worst case O(n)) 📖 Key Learning: This problem strengthened my understanding of tree traversal, recursion, and base case handling. It also reinforced how breaking a problem into smaller subproblems makes tree problems much easier to solve 💡 #DSA #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #BinaryTree #Recursion
To view or add a comment, sign in
-
-
🚀 Day 11.3 of Java DSA Journey —The Problem That Starts Everything 🧠 📌 Problem: Fibonacci Number (LeetCode 509) Most people learn Fibonacci as a simple sequence… But today I realized: 👉 It’s the foundation of Dynamic Programming 💡 Core Idea Each number depends on the previous two: 👉 F(n) = F(n-1) + F(n-2) Simple formula. Powerful concept. 🧠 Key Learnings 🔹 Recursion vs Iteration Recursion is intuitive… but inefficient 🔹 Avoid Recalculation Naive recursion → O(2ⁿ) time ❌ Iterative approach → O(n) time ✅ 🔹 Space Optimization No need for arrays — just 2 variables ⚡ Complexity ⏱ Time: O(n) 📦 Space: O(1) 🔥 Pro Tips (Interview Level) 💡 Tip 1: Recognize Overlapping Subproblems If the same values are recomputed → think DP 💡 Tip 2: Start with Base Cases F(0) = 0, F(1) = 1 → everything builds from here 💡 Tip 3: Optimize Space Early If you only need last 2 values → don’t store everything 💡 Tip 4: Think Bottom-Up Iteration often beats recursion in interviews 💡 Tip 5: This Pattern Repeats Everywhere Fibonacci appears in: 1.Climbing Stairs 2.DP problems 3.Optimization challenges 🔥 Real Insight This problem taught me: ❌ Don’t just follow recursion blindly ✅ Understand the cost of recomputation That’s the difference between: 👉 Writing code 👉 Designing efficient solutions Consistency builds systems 📈 #DSA #LeetCode #Java #CodingJourney #DynamicProgramming #ProblemSolving #InterviewPrep #Day11 #BitManipulation #InterviewPrep #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper
To view or add a comment, sign in
-
🚀 Day 55: The Power of Polymorphism in Java 🎭 Today was a deep dive into one of the most powerful concepts in Object-Oriented Programming: Polymorphism (Greek for "Many Forms"). It’s the ability of an object to take on different forms depending on the context. In Java, I learned that this flexibility happens at two distinct stages: 1. Compile-Time Polymorphism (Static Binding) ⏱️ This is achieved through Method Overloading. ▫️ The Logic: Defining multiple methods in the same class with the same name but different parameters (type, number, or order). ▫️ The Benefit: It improves code readability and allows us to perform similar operations with different types of data without inventing new method names. Why "Compile-Time"? The compiler knows exactly which method to call just by looking at the arguments you provide. 2. Runtime Polymorphism (Dynamic Binding) 🏃♂️ This is achieved through Method Overriding. ▫️ The Logic: When a subclass provides a specific implementation of a method that is already defined in its parent class. ▫️ The Magic: We use Upcasting (Parent class reference pointing to a Child class object). The specific version of the method to be executed is determined while the program is actually running. ▫️ The Benefit: This is the secret to building flexible, scalable systems where you can add new features without breaking existing code. Question for the Java Community: In your experience, what’s a real-world scenario where Runtime Polymorphism saved you from writing massive if-else or switch blocks? I’d love to hear your examples! 👇 #Java #OOPs #Polymorphism #100DaysOfCode #BackendDevelopment #CleanCode #SoftwareEngineering #LearningInPublic #JavaDeveloper 10000 Coders Meghana M
To view or add a comment, sign in
-
Day 10.2 of Java with DSA Journey 🚀 📌 Problem: Base 7 Conversion (LeetCode 504) At first, this looks like a simple math problem… But it actually teaches something deeper: 👉 How numbers are built in different systems 💡 Core Idea To convert a number from base 10 → base 7: Divide by 7 Store remainder Repeat until 0 Reverse the result 🧠 Key Learnings 🔹 Understanding Number Systems Decimal (base 10) is just one system—this logic works for ANY base 🔹 Modulo + Division Pattern num % base → current digit num / base → move to next position 🔹 Why Reverse? We generate digits from least significant → most significant ⚡ Complexity ⏱ Time: O(log₇ n) 📦 Space: O(log₇ n) 🔥 Pro Tips (Interview Level) 💡 Tip 1: This is a Universal Pattern This exact logic works for: Binary (base 2) Octal (base 8) Hex (base 16) 👉 Learn once, apply everywhere. 💡 Tip 2: Handle Negatives Separately Always convert using abs(num) and attach - later This avoids tricky modulo behavior. 💡 Tip 3: Avoid String Concatenation in Loops Use StringBuilder 👉 Shows awareness of time complexity + memory efficiency 💡 Tip 4: Reverse Thinking = Interview Gold If you're building output backward → think reverse at the end 💡 Tip 5: Hidden Optimization Insight If allowed, you could also: Use recursion → cleaner logic Or pre-calculate size for optimization 🔥 Real Insight This problem is not about Base 7… It’s about understanding: 👉 How computers represent and transform numbers internally Once you master this, you can convert between any number systems. Consistency builds depth 📈 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #Algorithms #MathLogic #Day10 #BitManipulation #InterviewPrep #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper
To view or add a comment, sign in
-
-
Day 10 of Java DSA Journey 🚀 📌 Problem: Power of Two (LeetCode 231) Most people solve this using loops: ➡️ Keep dividing by 2 until you reach 1 But today I learned something better: 👉 You can solve it in ONE line using bit manipulation 🤯 💡 Core Idea A number is a power of two if: ✔️ It has only one ‘1’ in its binary form Examples: 1 → 0001 2 → 0010 4 → 0100 16 → 10000 🧠 The Magic Trick 👉 n & (n - 1) This removes the rightmost set bit So: If result = 0 → only one bit was set → ✅ Power of Two Else → ❌ Not a power of two ⚡ Complexity ⏱ Time: O(1) 📦 Space: O(1) 🔥 Pro Tips (Interview Level) 💡 Tip 1: Always Check Positivity First n > 0 is mandatory — bit tricks fail for negative numbers. 💡 Tip 2: Understand, Don’t Memorize n - 1 flips: the rightmost 1 → 0 all bits after it → 1 That’s why the trick works. 💡 Tip 3: This Pattern Appears Everywhere The same trick is used in: Counting set bits Subset generation Low-level optimizations 👉 Learn it once, reuse forever. 💡 Tip 4: Alternative Trick (Even Cleaner) Another way: 👉 (n & -n) == n This isolates the lowest set bit. If it's equal to n, only one bit exists. 💡 Tip 5: Bitwise = Senior-Level Thinking Using bit manipulation shows: ✔️ You understand how data is stored ✔️ You can optimize beyond brute force 🔥 Real Insight This problem is not about checking powers… It’s about recognizing: 👉 Patterns in binary representation Once you see that, the solution becomes obvious. Consistency builds mastery 🔑 #DSA #LeetCode #Java #BitManipulation #CodingJourney #ProblemSolving #InterviewPrep #Day10 #BitManipulation #InterviewPrep #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Binary Tree Preorder Traversal (LeetCode 144) 💻 Language: Java 🔹 Approach: To solve this problem, I used Depth-First Search (DFS) with Recursion to perform preorder traversal of the binary tree. • Visit the root node first • Store the root value in the result list • Recursively traverse the left subtree • Recursively traverse the right subtree • Follow Preorder pattern: Root → Left → Right This approach works efficiently because recursion naturally follows the preorder traversal structure. ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(n) (including recursion stack) 📖 Key Learning: This problem strengthened my understanding of DFS, recursion, and tree traversal patterns. It also reinforced the preorder pattern (Root → Left → Right), which is a fundamental concept used in many tree-based problems 💡 #DSA #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #BinaryTree #DFS #Recursion #TreeTraversal
To view or add a comment, sign in
-
-
💡 Understanding the var Keyword in Java While learning modern Java, I came across the var keyword — a small feature that makes code cleaner, but only when used correctly. Here’s how I understand it 👇 In Java, when we declare a variable using var, the compiler automatically determines its data type based on the value assigned. For example: java var name = "Akash"; Here, Java infers that name is of type String. ⚠️ One important clarification: It’s not the JVM at runtime — type inference happens at compile time, so Java remains strongly typed. ### 📌 Key Rules of var ✔️ Must be initialized at the time of declaration java var a = "Akash"; // ✅ Valid var b; // ❌ Invalid ✔️ Can only be used inside methods (local variables) ❌ Not allowed for: * Instance variables * Static variables * Method parameters * Return types ### 🧠 Why use var? It helps reduce boilerplate and makes code cleaner, especially when the type is obvious: java var list = new ArrayList<String>(); ### 🚫 When NOT to use it Avoid `var` when it reduces readability: java var result = getData(); // ❌ unclear type ✨ My takeaway: `var` doesn’t make Java dynamic — it simply makes code more concise while keeping type safety intact. I’m currently exploring Java fundamentals and system design alongside frontend development. Would love to hear how you use var in your projects 👇 Syed Zabi Ulla PW Institute of Innovation #Java #Programming #LearningInPublic #100DaysOfCode #Developers #CodingJourney
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Binary Tree Inorder Traversal (LeetCode 94) 💻 Language: Java 🔹 Approach: To solve this problem, I used Depth-First Search (DFS) with Recursion to perform inorder traversal of the binary tree. • Recursively traverse the left subtree • Visit the root node and store its value • Recursively traverse the right subtree • Follow Inorder pattern: Left → Root → Right This approach works efficiently because recursion naturally follows the inorder traversal structure. ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(n) (including recursion stack) 📖 Key Learning: This problem strengthened my understanding of DFS, recursion, and tree traversal patterns. It also reinforced the inorder pattern (Left → Root → Right), which is a fundamental concept used in many tree-based problems 💡 #DSA #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #BinaryTree #DFS #Recursion #TreeTraversal
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