🔥 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
Permutations in-Place Backtracking with Swapping
More Relevant Posts
-
🚀 Day 67 of #100DaysOfCode Today’s problem focused on 2D Prefix Sum optimization — Range Sum Query 2D – Immutable (NumMatrix) 📊 At first glance, this problem looks like repeated matrix traversal, but the real win comes from preprocessing smartly. 📌 Problem Summary You’re given a 2D matrix and multiple queries asking for the sum of elements inside a sub-rectangle. Brute force would be too slow for repeated queries. 🧠 My Approach: Prefix Sum (Row-wise) Precompute prefix sums for each row For every query, calculate the sum in O(rows) time using prefix subtraction Avoid recalculating sums for every query This transforms repeated heavy computation into a fast query process ⚡ ⚙️ Time & Space Complexity Preprocessing: O(rows × cols) Each Query: O(rows) Space: O(rows × cols) 🔥 Key Learning Prefix sums are not limited to 1D arrays— they scale beautifully to 2D problems and are extremely powerful for range queries. Another solid step forward in mastering optimization techniques 💪 On to Day 68 🚀 #Day67 #100DaysOfCode #Java #LeetCode #PrefixSum #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
📅 Day 107 of #160DaysOfDSA 🔐 Decode the String ✅ Today’s problem helped me understand how stacks simplify decoding nested string patterns in an clean and structured way. 🧠 Problem in Short Given an encoded string of the form: k[encoded_string] ▪️ The substring inside [] must be repeated k times ▪️ Nested encodings are allowed 🔹 Example: Input: 3[b2[ca]] Output: bcacabcacabcaca 🚀 Core Idea We decode the string by traversing it character by character and using two stacks: 🔸 Count Stack → stores repetition numbers 🔸 String Stack → stores previous partial strings 🔁 Execution Flow ✔️ If digit → build the number ✔️ If [ → save current state (number + string) ✔️ If ] → • repeat current string • attach it to the previous string ✔️ If alphabet → append to the current string ⏱️ Complexity Time: O(n × k) Space: O(n) #DSA #Stack #DecodeString #GeeksForGeeks #ProblemSolving #Java #CodingJourney #GFG #Day107 #StringBuilder
To view or add a comment, sign in
-
-
LeetCode Practice - 944. Delete Columns to Make Sorted 🧠 Problem Idea ✅ You are given n strings, all of the same length. ✅ Imagine them written one below another like a grid. Example: cba daf ghi We check column by column. Column 0 → c d g → sorted ✅ Column 1 → b a h → NOT sorted ❌ Column 2 → a f i → sorted ✅ So we delete column 1 → answer = 1 🛠️ Key Observation ✅ A column is sorted if characters do not decrease from top to bottom. That means: 📌 strs[0][col] <= strs[1][col] <= strs[2][col] <= ... ✅ If any pair breaks this rule, that column must be deleted. 🚀 Algorithm 🔷 Take number of rows n 🔷 Take the n strings 🔷 For each column 🔷 Compare every row with the next row 🔷 If upperRowChar > lowerRowChar, mark it as invalid 🔷 Count how many columns are invalid #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🔥 Day 309 – Daily DSA Challenge! 🔥 Problem: 🔁 Permutations II Given an array nums that may contain duplicate numbers, return all unique permutations in any order. 💡 Key Insights: 🔹 This is a backtracking problem with an extra twist — duplicates. 🔹 Sorting the array upfront is the key to handling duplicates cleanly. 🔹 Use a used[] boolean array to track which elements are already in the current permutation. 🔹 The golden rule to skip duplicates 👇 👉 If the current number is the same as the previous one and the previous one is not used, skip it. 🔹 This ensures we only generate unique permutations. ⚡ Optimized Plan: ✅ Sort the input array ✅ Use backtracking to build permutations ✅ Track used elements with a boolean array ✅ Add permutation to result when its size equals nums.length ✅ Skip duplicates using: if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; ✅ Backtrack after each recursive call ✅ Time Complexity: O(n! × n) (due to copying permutations) ✅ Space Complexity: O(n) (recursion stack + used array) 💬 Challenge for you: 1️⃣ Why does the condition !used[i - 1] matter for avoiding duplicates? 2️⃣ How would this solution change if all numbers were unique? 3️⃣ Can you generate permutations iteratively instead of using recursion? #DSA #Day309 #LeetCode #Permutations #Backtracking #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
#PostLog116 𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 556 | 𝐍𝐞𝐱𝐭 𝐆𝐫𝐞𝐚𝐭𝐞𝐫 𝐄𝐥𝐞𝐦𝐞𝐧𝐭 𝐈𝐈𝐈 (𝐉𝐚𝐯𝐚) 𝐍𝐞𝐱𝐭 𝐆𝐫𝐞𝐚𝐭𝐞𝐫 𝐄𝐥𝐞𝐦𝐞𝐧𝐭 𝐈𝐈𝐈 using a 𝐧𝐞𝐱𝐭 𝐩𝐞𝐫𝐦𝐮𝐭𝐚𝐭𝐢𝐨𝐧–𝐛𝐚𝐬𝐞𝐝 𝐚𝐩𝐩𝐫𝐨𝐚𝐜𝐡, ensuring optimal time complexity and clean logic. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝐢𝐧 𝐛𝐫𝐢𝐞𝐟: ~ Traverse from right to left to find the first decreasing digit (pivot) ~ Identify the smallest digit greater than the pivot on the right side ~ Swap them to form a larger number ~ Reverse the suffix to get the smallest possible greater permutation ~ Carefully handle 32-bit integer overflow #LeetCode #Java #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 9 of Daily DSA 🚀 Solved LeetCode 11: Container With Most Water ✅ 🔍 Approach: Used the two-pointer technique to efficiently calculate the maximum area. Started with pointers at both ends Calculated area using min height × width Moved the pointer with the smaller height to optimize the result This avoids brute force and ensures an optimal solution. ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 5 ms (Beats 80.63%) • Memory: 77.19 MB (Beats 92.56%) A great example of how the right observation can turn a problem into a clean solution. #DSA #LeetCode #Java #TwoPointers #ProblemSolving #Consistency #DailyCoding
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
-
-
🚀 #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
-
-
Day 51/100 – LeetCode Challenge ✅ Problem: #3634 Minimum Removals to Balance Array Difficulty: Medium Language: Java Approach: Sorting + Sliding Window Time Complexity: O(n log n) Space Complexity: O(1) Key Insight: After sorting, valid subarray must satisfy nums[j] ≤ nums[i] × k for all elements. Find longest valid subarray using sliding window, then minimum removals = n - maxLen. Solution Brief: Sorted array to bring comparable values together. Used two pointers: expand j, shrink i when condition fails. Tracked maximum window length where nums[j] ≤ nums[i] × k. Result = total elements - longest valid subarray length. #LeetCode #Day51 #100DaysOfCode #SlidingWindow #Sorting #Java #Algorithm #CodingChallenge #ProblemSolving #MinimumRemovals #MediumProblem #Array #TwoPointers #DSA
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
-
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
Great consistency 🔥, keep learning ✨ Vikramaditya Singh