🚀 Day 46 Out of #365DaysOfCode - LeetCode Github link: https://lnkd.in/gGUy_MKZ Today I have solved the classic Permutations II problem, where the goal is to generate all unique permutations of an array that may contain duplicate elements. To handle duplicates efficiently, I implemented a backtracking approach combined with: 🔹 Sorting the input array 🔹 A boolean used[] array to track visited elements 🔹 A pruning condition to skip duplicate branches This approach avoids redundant computations and ensures only distinct permutations are generated. 💡 Key Learnings: How to design efficient recursive solutions Managing state during backtracking Handling duplicates in combinatorial problems Improving performance with pruning techniques This problem strengthened my understanding of recursion trees and optimization strategies in algorithm design. #Java #Backtracking #DataStructures #Algorithms #CodingPractice #ProblemSolving #Recursion #SoftwareDevelopment
LeetCode Permutations II Solution in Java
More Relevant Posts
-
🚀 24/02/26 — From Rotations to Root Nodes: Today’s DSA Wins Today I tackled some clever problems that pushed me to think differently about strings and trees. Here’s a quick breakdown of what I learned and implemented: 🔄 Strobogrammatic Numbers — LeetCode 246 A number that looks the same when rotated 180° (like "69" or "88"). Approach: Used a Two-Pointer technique with a rotation map including '0', '1', '8', '6', and '9'. Complexity: O(N) Time and O(1) Space. Result: 100% runtime beats (0ms). 🧵 Append Characters to Make Subsequence — LeetCode 2486 Goal: Find the minimum characters to append so that string t becomes a subsequence of string s. Approach: Applied a Greedy Two-Pointer strategy to match characters while traversing both strings. Complexity: O(N + M) Time and O(1) Space. 🌳 LCA of Binary Tree III — LeetCode 1650 Nodes have parent pointers, which made this problem fascinating. I implemented two approaches: Approach 1 — HashSet Ancestor Tracking: Store all ancestors of node p in a HashSet, then check node q’s ancestors against it. Efficiency: O(N) Time , O(N) Space. 🚀 Approach 2 — Linked List Intersection Trick: Treat paths to the root as two intersecting linked lists. Redirect pointers when reaching null so they meet at the Lowest Common Ancestor. Efficiency: O(N) Time , O(1) Space. 💡 Lightbulb Moment Realizing that the Intersection of Two Linked Lists pattern works perfectly for trees with parent pointers was a game-changer. Today was proof that pattern mastery > memorizing problems. Thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the guidance and high-quality resources that keep me learning. Visual notes + 100% runtime screenshots attached below! 📄👇 #DSA #Java #LeetCode #CodingJourney #TwoPointers #BinaryTree #Optimization #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
🚀 Day 12 of My LeetCode Journey Today I solved Group Anagrams (LeetCode 49). Problem: Given an array of strings, group the strings that are anagrams of each other. Approach: I used a HashMap to group words based on their sorted characters. If two words have the same sorted form, they belong to the same anagram group. Example: "eat", "tea", and "ate" → sorted form "aet" → same group. Key Concepts: • HashMap • String sorting • Hashing technique for grouping Time Complexity: O(n × k log k) Space Complexity: O(n × k) This problem is a great example of using hashing to classify data efficiently. #leetcode #datastructures #algorithms #java #codinginterview #softwareengineering
To view or add a comment, sign in
-
-
🚀 07/03/26 — Leveling Up: Mastering Binary Tree Level Order Traversal Today's session was all about shifting from depth-based exploration to breadth-based traversal. I implemented the Level Order Traversal (LeetCode 102), which is the foundation for Breadth-First Search (BFS) in trees. 🌊 Level Order Traversal (BFS) Unlike Preorder or Inorder which dive deep into branches, Level Order visits the tree layer by layer, from top to bottom and left to right. The Logic: Initialize a Queue to keep track of nodes at the current and next levels. Add the root to the queue to start. The Level-By-Level Strategy: Inside the main while loop, I capture the current size of the queue. This ensures that I only process nodes belonging to the current level before moving to the next. For each node processed, add its value to the current level list and enqueue its left and right children if they exist. Complexity: Time: O(N) because every node is enqueued and dequeued exactly once. Space: O(N) to hold the queue, which at most contains the maximum width of the tree. 📊 Implementation Highlights FeaturePreorder/Inorder (Yesterday)Level Order (Today)StrategyDepth-First Search (DFS)Breadth-First Search (BFS)Data StructureStack (FILO)Queue (FIFO)Traversal PathFollows branches to the leafVisits layer by layer📈 Consistency Report Applying the Queue implementation I practiced on March 2nd to a Binary Tree problem was a perfect example of how different DSA topics connect. Using the size() of the queue to separate levels is a key interview pattern that I now feel very comfortable with. Huge thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the roadmap. Moving from depth-based logic to breadth-based flows is a major expansion of my tree-solving toolkit! My tested implementation for Level Order Traversal is attached! 📄👇 #DSA #Java #LeetCode #BinaryTree #BFS #Queue #CodingJourney #LevelOrderTraversal #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
-
🚀 Day 13/100 — Recursive Deconstruction Today’s Challenge: LeetCode 761 - Special Binary String 🧩 Yesterday was about bits; today was about Structural Grammar. Special Binary Strings aren't just 1s and 0s; they are a language. The Realization: A special string is like a valid set of parentheses. 1 is ( and 0 is ). To find the "lexicographically largest" version, you have to break the string into its most basic components, sort them, and put them back together. My 0ms Optimization Strategy: 1. Mental Mapping: Treated the string as a nested structure. If 1...0 is a special string, I stripped the outer layer, solved the inside, and then re-wrapped it. 2. Greedy Reassembly: Used Collections.sort() with a reverse comparator. In binary, "larger" just means the 1s appear as early as possible. 3. Memory Management: Minimized object creation by identifying "split points" first before committing to substring allocations. Reflection: Sometimes the fastest way to solve a problem isn't to iterate forward, but to look at the problem as a recursive tree. Every "Special" chunk is a node that can be reordered to maximize the total value. 13 days down. The logic is getting deeper. 87 days to go. 🛠️ #Java #DSA #LeetCode #100DaysOfCode #Recursion #StringAlgorithms #SoftwareEngineer #CodingJourney #Optimization
To view or add a comment, sign in
-
-
Day 70 - LeetCode Journey Solved LeetCode 88: Merge Sorted Array (Easy) today — a classic problem that focuses on array manipulation and the two-pointer technique. The challenge is to merge two sorted arrays into one sorted array without using extra space, by modifying nums1 in-place. 💡 Core Idea: Instead of merging from the beginning, we start from the end of the arrays. Why? Because nums1 already has extra space at the end to accommodate elements from nums2. We use three pointers: • i → last valid element in nums1 • j → last element in nums2 • k → last position of merged array At each step, we place the larger element at position k, ensuring the array remains sorted. ⚡ Key Learning Points: • Using the two-pointer technique from the end • Performing in-place array merging • Maintaining O(m + n) time complexity • Avoiding unnecessary extra space This problem is a great reminder that sometimes changing the direction of traversal makes the solution much simpler. ✅ Better understanding of array manipulation ✅ Stronger grasp of two-pointer techniques ✅ Improved problem-solving efficiency Small problems like this build strong fundamentals for bigger challenges 🚀 #LeetCode #DSA #Java #TwoPointers #Arrays #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 42 of #100DaysOfCode Solved 1508. Range Sum of Sorted Subarray Sums on LeetCode 📊 🧠 Problem Insight: Given an array, we must compute the sum of all subarray sums, sort them, and return the sum of elements between indices left and right. ⚙️ Approach Used: 1️⃣ Generate all possible subarray sums using nested loops 2️⃣ Store them in an array of size n*(n+1)/2 3️⃣ Sort the subarray sums 4️⃣ Compute the sum of elements from index left-1 to right-1 5️⃣ Apply mod = 1e9 + 7 to avoid overflow This approach works well because the total number of subarrays is manageable for the given constraints. ⏱️ Time Complexity: O(n² log n) O(n²) to generate subarray sums O(n² log n) to sort them 📦 Space Complexity: O(n²) #100DaysOfCode #LeetCode #DSA #Arrays #Algorithms #Java #CodingPractice #InterviewPrep
To view or add a comment, sign in
-
-
🚀 LeetCode Problem || Fancy Sequence (1622) Today I worked on an interesting design problem where we need to maintain a sequence that supports the following operations efficiently: • append(val) → Append a number to the sequence • addAll(inc) → Add a value to every element in the sequence • multAll(m) → Multiply every element by a value • getIndex(idx) → Retrieve the value at a specific index 💡 Optimization Idea Instead of modifying every element, we represent the sequence transformation using a mathematical form: value=a×x+bvalue = a \times x + bvalue=a×x+bWhere: a tracks the cumulative multiplication b tracks the cumulative addition x is the stored base value #LeetCode #Java #Algorithms #DataStructures #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 66 - LeetCode Journey Solved LeetCode 167: Two Sum II – Input Array Is Sorted (Medium) today — a great example of how knowing the properties of a sorted array can drastically simplify the solution. Since the array is already sorted in non-decreasing order, we can avoid extra data structures and use a two-pointer approach to find the pair efficiently. 💡 Core Idea: Start with two pointers: • left at the beginning • right at the end Then check the sum of the two numbers: If the sum is equal to the target → solution found If the sum is less than the target → move the left pointer forward If the sum is greater than the target → move the right pointer backward This gradually narrows down the search space until the correct pair is found. ⚡ Key Learning Points: • Leveraging sorted array properties • Efficient use of the two-pointer technique • Reducing time complexity to O(n) • Solving the problem with O(1) extra space Problems like this highlight how choosing the right technique can make solutions clean, fast, and elegant. ✅ Stronger understanding of two-pointer patterns ✅ Better optimization mindset ✅ Improved problem-solving intuition Every problem solved adds another useful pattern to the toolkit 🚀 #LeetCode #DSA #Java #TwoPointers #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperJourney #KeepCoding
To view or add a comment, sign in
-
-
Today I solved LeetCode 145 – Binary Tree Postorder Traversal. 🧩 Problem Summary: Given the root of a binary tree, return the postorder traversal of its nodes' values. In postorder traversal, nodes are visited in the order: Left → Right → Root 💡 Key Concepts Used: Binary Trees Tree Traversal Iterative approach using Stack Depth First Search (DFS) 🧠 Approach: Use a stack to simulate recursion. Traverse to the leftmost node while pushing nodes onto the stack. Peek the node at the top of the stack. If the node has a right child that hasn’t been processed, move to the right subtree. Otherwise, process the node (add it to the result) and mark it as last visited. Repeat until all nodes are processed. This ensures the correct Left → Right → Root traversal order. 📚 What I Learned: How to implement postorder traversal iteratively. Managing traversal state using a stack and lastVisited pointer. Understanding the difference between recursive and iterative tree traversal. Strengthening concepts of Depth First Search (DFS) in binary trees. Exploring tree problems to build a stronger DSA foundation 🌳 Consistency in learning every day 🚀 #LeetCode #DSA #BinaryTree #TreeTraversal #PostorderTraversal #Stack #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Today I solved LeetCode 145 – Binary Tree Postorder Traversal. 🧩 Problem Summary: Given the root of a binary tree, return the postorder traversal of its nodes' values. In postorder traversal, nodes are visited in the order: Left → Right → Root 💡 Key Concepts Used: Binary Trees Tree Traversal Iterative approach using Stack Depth First Search (DFS) 🧠 Approach: Use a stack to simulate recursion. Traverse to the leftmost node while pushing nodes onto the stack. Peek the node at the top of the stack. If the node has a right child that hasn’t been processed, move to the right subtree. Otherwise, process the node (add it to the result) and mark it as last visited. Repeat until all nodes are processed. This ensures the correct Left → Right → Root traversal order. 📚 What I Learned: How to implement postorder traversal iteratively. Managing traversal state using a stack and lastVisited pointer. Understanding the difference between recursive and iterative tree traversal. Strengthening concepts of Depth First Search (DFS) in binary trees. Exploring tree problems to build a stronger DSA foundation 🌳 Consistency in learning every day 🚀 #LeetCode #DSA #BinaryTree #TreeTraversal #PostorderTraversal #Stack #Java #CodingJourney #ProblemSolving #100DaysOfCode
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