Day 22/30 – LeetCode streak Problem: Find Unique Binary String You are given 'n' distinct binary strings of length 'n' and must return any binary string of length 'n' that doesn’t appear in the array. Core idea (Cantor’s diagonal argument) * Think of 'nums' as an 'n × n' matrix of characters. * Look at the diagonal positions: character 'i' of string 'nums[i]'. * Build a new string where the 'i'-th character is the flip of 'nums[i].charAt(i)' ('0' → '1', '1' → '0'). * This constructed string differs from 'nums[0]' at index '0', from 'nums[1]' at index '1', …, from 'nums[i]' at index 'i', so it cannot be equal to any string in 'nums'. * Time complexity: 'O(n)', space: 'O(n)' for the output string. Day 22 takeaway: This problem is a neat, direct application of Cantor’s diagonalization: by flipping the diagonal bits, you guarantee a new string that is different from every given one in at least one position, without any searching or backtracking. #leetcode #dsa #java #strings #consistency
LeetCode Day 22: Cantor's Diagonal Argument
More Relevant Posts
-
Day 28/30 – LeetCode streak Problem: The k-th Lexicographical String of All Happy Strings of Length n A happy string is length 'n' over '{a,b,c}' with no two adjacent characters equal. Core idea * Total happy strings of length 'n': * First character: 3 choices ('a','b','c'). * Each of the remaining 'n-1' positions: 2 choices (anything different from the previous character). * So 'total = 3 * 2^(n-1)'. If 'k > total', the answer is an empty string. * Instead of generating all strings, we can index them directly: * Fixing the first character divides the list into blocks. * Each first character corresponds to a block of '2^(n-1)' strings. * Compute 'block = 1 << (n-1)'. * 'firstIdx = (k-1) / block' → '0 → a', '1 → b', '2 → c'. * 'rem = (k-1) % block' determines the remaining 'n-1' choices. * For each remaining position: * Look at the previous character. * The next character must be one of the two letters different from it, taken in lexicographic order. * Use bits of 'rem' to choose between the smaller or larger valid option. This lets us map 'k' directly to the correct happy string in 'O(n)' time without generating all combinations. Day 28 takeaway: Happy strings follow a clean combinatorial pattern of '3 * 2^(n-1)'. Treating the suffix as a binary decision sequence lets you construct the k-th string directly instead of using backtracking or BFS. #leetcode #dsa #java #strings #combinatorics #consistency
To view or add a comment, sign in
-
-
🚀 LeetCode Practice Update Solved “1415. The k-th Lexicographical String of All Happy Strings of Length n” today. It’s an easy–medium problem for anyone comfortable with Backtracking, but a great exercise to strengthen recursive thinking and constraint-based generation. 🧠 Approach The idea is to generate all valid “happy strings” using backtracking and then simply pick the k-th string in lexicographical order. A happy string means: It only contains characters 'a', 'b', 'c' No two adjacent characters are the same ⚙️ Strategy 1. Start with an empty string and recursively build all possible strings of length n. 2. At each step, try adding characters from 'a' → 'c' to maintain lexicographical order. 3. Before adding a character, check the constraint: If the last character of the current string is the same as the character we want to add → skip it. 4. If the string length becomes n, add it to the list of valid happy strings. 5. After generating all valid strings: If k > total strings, return an empty string. Otherwise return the (k-1)th index from the list. 🔁 Key Backtracking Step After exploring a choice, we remove the last character to restore the previous state and try the next option. This pattern of choose → explore → undo (backtrack) is the heart of backtracking problems. 💡 Problems like this really show how powerful backtracking can be when generating all valid combinations under constraints. #LeetCode #Backtracking #Java #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 30 Problem: 2840. Make Two Strings Equal by Swapping Topic: String, Hash Table, Math, Parity 📌 Quick Problem Sense: Two strings of length n. You can swap characters at indices i and j only if j - i is even — on either string, any number of times. Can you make both strings identical? 🤔 This is the natural generalization of yesterday's Day problem same core insight, arbitrary length! 🧠 Approach (Simple Thinking): 🔹 j - i even means i and j have the same parity (both even or both odd) 🔹 So even-indexed positions can only swap among themselves — and since ANY two even positions can swap, they're fully freely rearrangeable 🔹 Same story for odd-indexed positions — completely isolated from even ones 🔹 The strings can be made equal if and only if: multiset(s1[even indices]) == multiset(s2[even indices]) ✅ multiset(s1[odd indices]) == multiset(s2[odd indices]) ✅ 🔹 Use a frequency difference array per parity — one pass, O(n) time, O(1) space 🎯 🔹 If all differences cancel to zero → true, otherwise → false ⏱️ Time Complexity: Single pass through both strings → O(n) 📦 Space Complexity: 2 × 26 frequency counters → O(1) 💡 Connection to Day 29: Yesterday's problem (length 4, fixed swaps 0↔2 and 1↔3) is just a special case of today! The insight is identical — parity groups are isolated. Today it scales to any n. Same thinking, bigger input! 🔗 https://lnkd.in/g_ExG2Xd I wrote a full breakdown with dry run, real-life analogy, side-by-side comparison with Day 29, and step-by-step code walkthrough here 👇 https://lnkd.in/gYHZZRrZ If you solved it by extracting even/odd subsequences, sorting them and comparing as strings, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving #Strings
To view or add a comment, sign in
-
-
🚀 LeetCode Problem || The k-th Lexicographical String of All Happy Strings of Length n A happy string is a string that: • Contains only 'a', 'b', 'c' • No two adjacent characters are the same For example: Valid → abc, ac, b Invalid → aa, baa 💡 Approach I Used: I used Backtracking to generate all possible happy strings while ensuring that the current character is not the same as the previous one. Since we try characters in the order 'a' → 'b' → 'c', the generated strings are already in lexicographical order. After generating the strings, we simply return the k-th string if it exists. #Backtracking #Recursion #Strings #LeetCode #ProblemSolving #Java
To view or add a comment, sign in
-
-
Day 18 of my #30DayCodeChallenge: The Art of String Manipulation! The Problem: Count and Say. A classic string problem where each term is generated by describing the previous term using Run-Length Encoding (RLE). The Logic: The key here is to simulate the process of "reading out loud" what you see. Using a StringBuilder and a two-pointer approach, we can efficiently build the next string in the sequence: 1. Iterative Progression: Starting from the base case "1", we loop n - 1 times to reach the n" term. 2. The Two-Pointer Scan: For each string, I used an inner whi le loop to find groups of identical consecutive characters. 3. Count and Append: * Count: Calculate the length of the run (number of times a digit repeats). *Say: Append the count followed by the digit itself to our StringBuilder. 4. Update & Repeat: The newly built string becomes the input for the next iteration. This problem is a great exercise in managing indices and understanding how strings are constructed dynamically in Java. One step closer to mastery. Onward to Day 19! #Java #Algorithms #DataStructures #LeetCode #ProblemSolving #150DaysOfCode #SoftwareEngineering #CodingLife #Strings
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 26 Problem: 3548. Equal Sum Grid Partition II Topic: Array, Matrix, Prefix Sum, HashSet, Greedy 📌 Quick Problem Sense: You're given an m × n integer grid. Make one straight cut, horizontal or vertical to split it into two non-empty parts with equal sums. The twist? You're allowed to remove at most one border element (right at the cut edge) from either side to balance the sums. Return true if such a partition is possible! 🧠 Approach (Simple Thinking): 🔹 Compute the total sum of the grid upfront 🔹 Scan row by row, maintain a running top sum, derive bottom = total - top 🔹 The imbalance is diff = top - bottom 🔹 A cut is valid if: diff == 0 → already perfectly balanced ✅ diff equals a corner cell of the top section ✅ diff equals the left-border cell of the current bottom row ✅ diff exists in a HashSet of all values seen so far ✅ 🔹 Use a HashSet to track all border values already scanned, O(1) lookup to check if removing one element fixes the imbalance 🔹 For vertical cuts → simply transpose the matrix and reuse the same horizontal cut logic! 🔹 Also try reversed row order to cover cuts scanned from the opposite direction, 4 passes total, all reusing the same function 🔄 ⏱️ Time Complexity: 4 passes through the grid (original, reversed, transposed, transposed+reversed) → O(m × n) Single scan per pass, HashSet lookups in O(1) — clean and efficient! 📦 Space Complexity: HashSet of seen values → O(m × n) worst case Transpose grid → O(m × n) Overall → O(m × n) I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/g2FHaT4S If you solved it by explicitly enumerating only the border cells, or used a different balance-check trick, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving #Programming
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 29 Problem: 3442. Make Two Strings Equal by Swapping Topic: String, Hash Table 📌 Quick Problem Sense: Two strings of length 4. You can swap characters at indices i and j only if j - i = 2. That means only swaps (0↔2) and (1↔3) are allowed, on either string, any number of times. Can you make both strings equal? 🤔 🧠 Approach (Simple Thinking): 🔹 Ask the key question first: which positions can actually interact? 🔹 Swap (0↔2) and (0↔1)? NEVER, gap must be exactly 2 🔹 So even positions {0, 2} are forever isolated from odd positions {1, 3} 🔹 Within each group of 2, you can freely swap, so any arrangement within the group is reachable 🔹 The strings are equalizable if and only if: {s1[0], s1[2]} and {s2[0], s2[2]} contain the same characters (even group) ✅ {s1[1], s1[3]} and {s2[1], s2[3]} contain the same characters (odd group) ✅ 🔹 Just sort each pair and compare, done! 🎯 ⏱️ Time Complexity: Fixed length 4 → everything is constant → O(1) 📦 Space Complexity: Four char arrays of size 2 → O(1) I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/g_ExG2Xd If you solved it with a frequency map or a different parity grouping trick, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟒 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding the minimum element in a rotated sorted array using binary search. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Minimum in Rotated Sorted Array 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used binary search to reduce the search space • Compared the middle element with the rightmost element Logic: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) • Continued until left meets right 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Rotated arrays require a modified binary search • Comparing with boundary elements helps identify the sorted half • Binary search is not only for exact matches • Reducing the search space is the core idea 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(log n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Binary search is about asking the right question — not just finding the middle. 54 days consistent 🚀 On to Day 55. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Day 15 of #50DaysLeetCode Challenge Today I solved the “Longest Common Prefix” problem on LeetCode using Java. 🔹 Problem: Find the longest common prefix among an array of strings. If no common prefix exists, return an empty string "". Example: Input: ["flower","flow","flight"] Output: "fl" Input: ["dog","racecar","car"] Output: "" 🔹 Approach I Used: ✔ Took the first string as the initial prefix ✔ Compared it with each string in the array ✔ If mismatch occurs, reduced the prefix step by step ✔ Continued until all strings share the same prefix 🔹 Key Insight: You don’t need complex logic — just keep shrinking the prefix until it matches all strings. 🔹 Concepts Practiced: • String manipulation • Iterative comparison • Edge case handling #LeetCode #DSA #Java #Algorithms #ProblemSolving #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Series – Longest Common Prefix 📌 Problem: Given an array of strings, the task is to find the longest common prefix shared by all the strings. If there is no common prefix, return an empty string "". Example: Input: "["flower","flow","flight"]" Output: ""fl"" Input: "["dog","racecar","car"]" Output: """" (no common prefix) 💡 Approach Used (Character by Character Comparison): 1️⃣ Take the first string in the array as a reference. 2️⃣ Traverse its characters one by one. 3️⃣ For each character, compare it with the same position in all other strings. 4️⃣ If any string has: - a different character, or - the length is smaller, then stop and return the prefix built so far. If all characters match across every string, keep adding them to the prefix. This approach checks characters column-wise across all strings. ⚡ Time Complexity: O(n × m) - n = number of strings - m = length of the smallest string ⚡ Space Complexity: O(1) #DSASeries #LeetCode #Java #CodingPractice #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