🔥 Day 97/100 of Code – Subsets II: Backtracking with Duplicate Pruning! Today solved a power set problem with duplicate elements — a clean extension of the classic subsets problem: ✅ Problem 90: Subsets II Task: Generate all unique subsets from an array that may contain duplicates. Approach: Sort + backtracking with level-skip logic: Sort array to group duplicates At each recursion level, iterate from ind to end: Skip duplicates: if (i != ind && nums[i] == nums[i-1]) continue Include nums[i], recurse with i+1 Backtrack Key Insight: The condition i != ind ensures we only take the first occurrence of a duplicate at each recursion depth, preventing duplicate subsets across different branches. Complexity: O(2^n) time worst-case, but pruning avoids duplicate subset generation. A subtle but crucial tweak to standard subset backtracking — handles real-world duplicate data elegantly! 🔄📦 #100DaysOfCode #LeetCode #Java #Backtracking #Subsets #DFS #Algorithm
Subsets II: Backtracking with Duplicate Pruning in Java
More Relevant Posts
-
🔥 Day 98/100 of Code – Permutations: In-Place Backtracking with Swapping! Today revisited the classic permutation problem using an elegant in-place swapping approach: ✅ Problem 46: Permutations Task: Generate all permutations of distinct integers. Approach: Recursive swapping with index tracking: Fix elements step-by-step by swapping them into position At level i, swap nums[i] with each nums[j] where j ≥ i Recurse to i+1, then backtrack by swapping back Base case: when i == nums.length, store current array state Key Insight: By swapping in-place, we avoid extra space for temporary lists and naturally generate permutations without duplicate checks (since elements are distinct). Complexity: O(n × n!) time, O(n) recursion depth — optimal for generating all permutations. A clean, memory-efficient backtracking technique — fundamental for combinatorial generation! 🔄🧩 #100DaysOfCode #LeetCode #Java #Backtracking #Permutations #DFS #Algorithm
To view or add a comment, sign in
-
-
You can see the actual use of the static keyword in a class in the form of a data member. In this code, the company class creates multiple objects, and each object gets its own copy of instance variables like id and name. However, the common part is company_name, which remains the same for everyone. So instead of wasting memory by creating multiple copies, we use a smart and memory-efficient approach by declaring company_name as a static data member. This ensures that only ONE copy of company_name is created and shared among all objects of the class 😎🔥 static = memory optimization + shared data #Java #OOPs #StaticKeyword #Programming #LearningJava #CodeLogic #DeveloperJourney 🚀
To view or add a comment, sign in
-
-
Day 53/100 – LeetCode Challenge ✅ Problem: #110 Balanced Binary Tree Difficulty: Easy Language: Java Approach: DFS with Early Termination Time Complexity: O(n) Space Complexity: O(h) where h = tree height Key Insight: Tree is balanced if for every node: Left and right subtrees are balanced Height difference ≤ 1 Use DFS to compute heights while checking balance condition. Return -1 as sentinel for unbalanced subtree. Solution Brief: Modified depth calculation to return -1 when imbalance detected. Checked left/right subtree heights at each node. If any subtree returns -1 or height difference > 1, propagate -1 upward. Final check: root depth ≠ -1 means tree is balanced. #LeetCode #Day53 #100DaysOfCode #DFS #Java #Algorithm #CodingChallenge #ProblemSolving #BalancedBinaryTree #EasyProblem #Tree #Recursion #DSA
To view or add a comment, sign in
-
-
Day 42/100 – LeetCode Challenge ✅ Problem: #127 Word Ladder Difficulty: Hard Language: Java Approach: BFS with Character Replacement Time Complexity: O(M² × N) where M = word length, N = word list size Space Complexity: O(N) Key Insight: Treat words as nodes; edge exists if words differ by one character. Use BFS to find shortest transformation sequence from beginWord to endWord. Generate all possible one-character variations for each word. Solution Brief: Used queue with (word, distance) pairs. For each word, changed each character to 'a'-'z', checking if new word exists in wordList. Removed visited words from set to prevent cycles. BFS for shortest transformation path in word graph #LeetCode #Day42 #100DaysOfCode #BFS #Java #Algorithm #CodingChallenge #ProblemSolving #WordLadder #HardProblem #Graph #StringManipulation #DSA
To view or add a comment, sign in
-
-
Day 8 | LeetCode – Delete Node in a Linked List Today, I solved Delete Node in a Linked List — a problem that tests understanding of pointer manipulation rather than traversal. The twist: We are given only the node to delete, not the head of the list. Instead of traditional deletion, the approach was: Copy the value of the next node into the current node Redirect the current node’s next pointer Disconnect the next node This makes the deletion possible in: ✅ Time Complexity: O(1) ✅ Space Complexity: O(1) What I liked about this problem is how it challenges assumptions. Normally, deleting a node requires access to the previous node — but here, the solution comes from modifying the current node itself. A great reminder that understanding data structure behavior deeply is more important than memorizing patterns. #Day8 #DSA #LeetCode #LinkedList #Java #ProblemSolving #Algorithms #InterviewPrep #DailyLearning
To view or add a comment, sign in
-
-
🚀 Day 47 Out of #365DaysOfCode - LeetCode Github link: https://lnkd.in/gGUy_MKZ Today I have worked on a classic problem: converting an integer into its corresponding Excel column title. At first glance, it looks like a simple base-26 conversion. But the interesting twist is that Excel columns are 1-based indexed and do not contain a zero character. That means we need to adjust the number before applying the modulus operation to correctly map values to letters. 💡 Key Learnings: Handling custom base conversions Managing edge cases with non-zero indexing Efficient string building using StringBuilder Strengthening problem-solving fundamentals ⏱️ Time Complexity: O(log₍26₎ n) #Java #DataStructures #Algorithms #ProblemSolving #CodingPractice
To view or add a comment, sign in
-
-
📁 File Handling 🌊Character streams deal with Unicode characters 🌍 👉 They are meant for text, not raw binary data like byte stream.| ✔️ FileWriter → can create a file if it doesn’t exist ✨ ❌ FileReader → never creates a file 👉 If file doesn’t exist → FileNotFoundException 🚫 Reading rules 📖 ✔️ read() returns -1 at end of file 🛑 ✔️ Correct pattern: while ((ch = reader.read()) != -1) 🔁 File deletion 🗑️ ✔️ file.delete() ✔️ Returns boolean (true / false) ❓ Why no exception? 👉 Because streams are irrelevant for delete ❌ Character streams CANNOT update content in the middle of a file ✔️ Same rule as byte streams Why? 🤔 👉 Files are linear 📏 👉 There is no “insert here” operation 👉 You can only read forward or write forward What “update” actually means in Java 🧠 There is ONLY one way 👇 1️⃣ Read entire file (FileReader) 📖 2️⃣ Modify content in memory (String / StringBuilder) 🧩 3️⃣ Rewrite entire file (FileWriter) ✍️ ✅ This is the only real update mechanism Append ≠ Update ⚠️ 👉 Files store bytes; FileReader interprets bytes as characters, FileInputStream does not. GitHub Link: https://lnkd.in/g9843mcC 🔖Frontlines EduTech (FLM) #Java #JavaIO #FileHandling #ByteStream #CharacterStream #FileInputStream #FileReader #Unicode #JVM #JavaConcepts #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #BackendDevelopment #Programming #Java #FileHandling #CharacterStreams #Unicode #FileReader #FileWriter #BackendConcepts #LearningInPublic
To view or add a comment, sign in
-
-
𝐉𝐚𝐯𝐚 𝐓𝐞𝐜𝐡 𝐃𝐫𝐨𝐩 ☕ | 𝐉𝐕𝐌 𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥𝐬 𝐭𝐡𝐚𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐦𝐚𝐭𝐭𝐞𝐫 𝐢𝐧 𝐩𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 If you work with Java long enough, performance issues stop being “magic” and start being JVM behavior. A quick mental model that pays dividends: 🧠 𝐒𝐭𝐚𝐜𝐤 One per thread Stores method frames, local variables, references Fast, predictable, and not managed by the GC StackOverflowError = deep recursion or massive frames 🧺 𝐇𝐞𝐚𝐩 Shared across threads Where objects live Managed by the Garbage Collector 👶 𝐘𝐨𝐮𝐧𝐠 𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐢𝐨𝐧 Most objects die here (Eden → Survivor) Optimized for fast allocation & frequent GC High churn is fine — long-lived objects are not 🧓 𝐎𝐥𝐝 𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐢𝐨𝐧 Objects that survived multiple GCs Expensive to collect Memory leaks usually show up here, not in Eden 📦 𝐌𝐞𝐭𝐚𝐬𝐩𝐚𝐜𝐞 Stores class metadata (not objects) Native memory, not heap Unbounded by default → bad classloading can crash your JVM 🔄 𝐂𝐥𝐚𝐬𝐬𝐥𝐨𝐚𝐝𝐢𝐧𝐠 Dynamic loading is powerful… and dangerous Custom classloaders + redeploys = classic Metaspace leaks If classes don’t unload, neither does memory 💡 𝐈𝐧𝐬𝐢𝐠𝐡𝐭 Most “Java is slow” problems are really object lifetime + allocation pressure + classloading mistakes. Know where your data lives, how long it lives, and who loads it — the JVM will do the rest. #Java #Kotlin #Scala #JVM #Performance #BackendEngineering #TechDrop #SoftwareEngineering
To view or add a comment, sign in
-
Day 41/100 – LeetCode Challenge ✅ Problem: #130 Surrounded Regions Difficulty: Medium Language: Java Approach: DFS from Boundary + In-Place Modification Time Complexity: O(m × n) Space Complexity: O(m × n) for recursion stack Key Insight: Only 'O's connected to boundary cannot be surrounded. Mark all boundary-connected 'O's via DFS, then convert remaining 'O's to 'X'. Solution Brief: Traversed all four boundaries, starting DFS from each 'O'. Used vis[][] to mark connected 'O's reachable from boundary. Final pass: convert unvisited 'O's (surrounded) to 'X'. Smart boundary-based approach for region detection #LeetCode #Day41 #100DaysOfCode #DFS #Java #Algorithm #CodingChallenge #ProblemSolving #SurroundedRegions #MediumProblem #Matrix #Graph #BoundaryTraversal #DSA
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode | Day 36 📌 LeetCode – Path Sum Today I solved the Path Sum problem using a recursive Depth-First Search (DFS) approach. Given a binary tree and a target sum, determine whether there exists a root-to-leaf path such that the sum of all node values equals the target. 💡 Approach: ✔ If the node is null, return false. ✔ If it's a leaf node, check whether the remaining sum equals the node value. ✔ Recursively subtract the current node value from targetSum. ✔ Check both left and right subtrees. ✔ If either returns true → path exists. ⏱ Complexity: Time Complexity: O(n) Space Complexity: O(h) — height of the tree Binary tree problems are all about mastering recursion and understanding base cases clearly. #Java #LeetCode #DSA #BinaryTree #Recursion #ProblemSolving
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