🚀 Day 93 of My 100 Days LeetCode Challenge | Java Today’s problem explored recursion and backtracking, focusing on generating valid strings under specific constraints. The challenge was to generate happy strings of length n, where: The string consists only of 'a', 'b', and 'c' No two adjacent characters are the same From all possible happy strings, the goal was to find the k-th lexicographical string. To solve this, I used a backtracking approach that builds the string step by step. At each step, we try adding characters while ensuring they don't match the previous character. This naturally generates all valid happy strings in lexicographical order. Once all valid strings are generated, we simply return the k-th one if it exists. ✅ Problem Solved: The k-th Lexicographical Happy String of Length n ✔️ All test cases passed (345/345) ⏱️ Runtime: 22 ms 🧠 Approach: Backtracking + Recursion 🧩 Key Learnings: ● Backtracking is ideal for generating constrained combinations. ● Pruning invalid states early improves efficiency. ● Recursion makes exploring possible paths intuitive. ● Lexicographical generation often comes naturally with ordered iteration. ● Constraint-based string generation is a common interview pattern. This problem was a great exercise in systematically exploring possibilities while enforcing constraints. 🔥 Day 93 complete — strengthening recursion and backtracking intuition. #LeetCode #100DaysOfCode #Java #Backtracking #Recursion #ProblemSolving #DSA #CodingJourney #Consistency
Java LeetCode Challenge: Kth Lexicographical Happy String
More Relevant Posts
-
🚀 Day 44 of #100DaysOfCode — Mastering HashSet Internals in Java Today I went deep into one of the most commonly used collections in Java — HashSet 🔥 Not just usage… but how it actually works internally. 🧠 What is HashSet? 👉 HashSet is backed by a HashMap 👉 Stores elements as keys with a dummy value ⚙️ How HashSet Adds an Element? add(element) ↓ hashCode() → object-specific logic ↓ hash = h ^ (h >>> 16) // bit spreading ↓ index = (n - 1) & hash // bucket index ↓ bucket check ↓ if empty → insert if collision: ↓ equals() check ↓ if duplicate → reject ❌ else: ↓ add to LinkedList ↓ if bucket size ≥ 8 and capacity ≥ 64 → convert to Tree ↓ if bucket size ≤ 6 → convert back to LinkedList 🔍 Key Concepts I Learned 🔹 1. hashCode() Converts object → integer Used to decide bucket location 🔹 2. equals() Used to check duplicate Same hashCode ≠ same object 🔹 3. Collision Handling Multiple elements in same bucket Stored as: LinkedList (< 8 elements) Red-Black Tree (≥ 8 elements) 🌳 Tree Conversion Rules Bucket size ≥ 8 → Tree Bucket size ≤ 6 → Back to LinkedList Capacity must be ≥ 64 for tree conversion 🔄 Rehashing (Very Important) Default capacity = 16 Load factor = 0.75 👉 Threshold = 16 × 0.75 = 12 When size exceeds 12: Capacity doubles → 32 All elements are rehashed New bucket positions are recalculated ⚡ Why HashSet is Fast? Average Time Complexity: O(1) Due to: Efficient hashing Bitwise index calculation Tree optimization for collisions 🧠 Final Takeaway 👉 hashCode decides bucket 👉 equals decides duplicate 👉 structure (List/Tree) depends on size This deep dive really helped me understand why overriding hashCode() and equals() is critical in real-world applications. 🙏 Special thanks to my mentor Suresh Bishnoi sir for guiding me through these concepts and helping me understand the internals so clearly! #Java #HashSet #DataStructures #BackendDevelopment #CodingJourney #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
🚀Day 24 of #75DaysofLeetCode LeetCode Problem Solved: Removing Stars From a String (2390) Today I solved the problem “Removing Stars From a String.” 🔹 Problem Statement: We are given a string containing characters and *. Each * removes the closest non-star character to its left, along with the * itself. The task is to return the final string after all stars are processed. 💡 Approach: The most efficient way to solve this is using a Stack-like approach. 1️⃣ Traverse the string from left to right. 2️⃣ If the character is not *, add it to the result (stack). 3️⃣ If the character is *, remove the last added character. 4️⃣ Continue until the string is processed. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String removeStars(String s) { StringBuilder sb = new StringBuilder(); for(char c : s.toCharArray()) { if(c == '*') { sb.deleteCharAt(sb.length() - 1); } else { sb.append(c); } } return sb.toString(); } } ✨ Key Learning: Using a stack or StringBuilder helps efficiently simulate the removal of the closest character on the left. #LeetCode #Java #DataStructures #ProblemSolving #CodingPractice #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 97 of My 100 Days LeetCode Challenge | Java Today’s problem was a solid exercise in matrix processing and prefix sum optimization. The goal was to count the number of submatrices whose sum is less than or equal to a given value (k). A brute-force approach would be too slow, so the key was to use 2D prefix sums to efficiently compute submatrix sums. By converting the matrix into a prefix sum matrix, we can calculate the sum of any submatrix in constant time, making the overall solution much more efficient. ✅ Problem Solved: Count Submatrices With Sum ≤ K ✔️ All test cases passed (859/859) ⏱️ Runtime: 7 ms 🧠 Approach: 2D Prefix Sum 🧩 Key Learnings: ● Prefix sums are powerful for optimizing repeated range sum queries. ● 2D prefix sums extend the same idea from arrays to matrices. ● Preprocessing can drastically reduce computation time. ● Avoiding brute force is key in large input problems. ● Matrix problems often become easier with the right transformation. This problem reinforced how preprocessing techniques like prefix sums can turn complex problems into efficient solutions. 🔥 Day 97 complete — sharpening matrix optimization and prefix sum skills. #LeetCode #100DaysOfCode #Java #PrefixSum #Matrix #Algorithms #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
100 Days of Coding Challenge – Day 30 📌 Problem: Find the Index of the First Occurrence in a String 💻 Language: Java 🧠 Concept Used: String Matching (Brute Force) 🔍 Platform: LeetCode Today’s challenge was to find the first occurrence of a substring (needle) in a given string (haystack). If not found, return -1. Example: Input: "sadbutsad", "sad" Output: 0 Approach: ✔ Traverse the string from index 0 to n - m ✔ Extract substring of length m at each position ✔ Compare it with the target string ✔ Return index immediately when match is found ✔ If no match → return -1 Time Complexity: O(n × m) Space Complexity: O(1) 🔗 Problem Link: https://lnkd.in/g2ktYFFS 🔗 Code: https://lnkd.in/gynFixSQ #100DaysOfCode #Day30 #Java #DSA #LeetCode #Strings #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 98 - #100DaysOfCode Today’s problem was all about string comparison and operations simulation in Java. 💡 Problem Insight: Given a list of operations like "++X", "X++", "--X", "X--", we need to compute the final value of X after performing all operations. ⚠️ One key learning today: In Java, always use .equals() for string comparison instead of ==. Using == compares references, not actual content — a very common mistake! 🧠 Approach: Initialize x = 0 Traverse through each operation Increment or decrement based on the operation string 📌 What I Improved Today: Better understanding of string handling in Java Avoiding common pitfalls in comparisons Writing cleaner conditional logic #Java #CodingJourney #LeetCode #100DaysOfCode #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 99 of My 100 Days LeetCode Challenge | Java Today’s problem was all about randomization and linked list traversal — a nice break from heavy DP and matrices. The challenge was to design a system that returns a random node’s value from a singly linked list, ensuring that every node has an equal probability of being chosen. Since linked lists don’t allow direct indexing, the key idea was to first determine the size of the list, and then generate a random index to fetch the corresponding node. This approach ensures uniform randomness while keeping the implementation simple and efficient. ✅ Problem Solved: Linked List Random Node ✔️ All test cases passed (8/8) ⏱️ Runtime: 11 ms 🧠 Approach: Linked List Traversal + Randomization 🧩 Key Learnings: ● Randomization problems require ensuring uniform probability distribution. ● Linked lists limit direct access, so traversal becomes essential. ● Precomputing size can simplify random selection. ● Sometimes simple approaches are the most effective. ● Understanding data structure limitations helps design better solutions. This problem highlighted how probability + data structures can come together in elegant ways. 🔥 Day 99 complete — sharpening my understanding of randomization and linked list behavior. #LeetCode #100DaysOfCode #Java #LinkedList #Randomization #Algorithms #ProblemSolving #DSA #CodingJourney #Consistency
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
-
-
Day 73 of #90DaysDSAChallenge Solved LeetCode 451: Sort Characters By Frequency Learned an important Java design concept today. Problem Overview: The task was to sort characters in a string based on descending frequency. What confused me initially: Why create a separate Freq class instead of just using HashMap and PriorityQueue directly? Key Learning: PriorityQueue stores one complete object at a time. For this problem, each item needs two pieces of data together: Character Frequency Example: Instead of storing: e and 2 separately We package them as: Freq('e', 2) That custom class acts like a container holding both values in one object, so PriorityQueue can compare and sort them correctly. Why this matters: This taught me that custom classes in Java are often not about complexity, they simply bundle related data into one manageable unit. Alternative approach: We can also use Map.Entry<Character, Integer> instead of creating a custom class, but building Freq makes the logic easier to understand while learning. Today’s takeaway: Not every class is for business logic — sometimes it exists just to package data cleanly. #Java #90DaysDSAChallenge #LeetCode #PriorityQueue #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
📘 Day 25 – Unlocking the Magic of Java Casting Today I dove deep into non-primitive type casting in Java and had that haha moment! 💡 ✨ Upcasting – Treating a subclass object as a superclass reference. It makes my code cleaner, flexible, and ready for change. ⚡ Downcasting – Converting back safely to a subclass. Done wrong, it throws ClassCastException, but done right, it’s pure power. 🛡 instanceof operator – My safety net! It checks object type before casting, keeping runtime errors away. Seeing objects flow up and down the hierarchy revealed the true beauty of polymorphism, code that’s adaptable, maintainable, and future-proof. 💬 What really clicked: Java isn’t just about syntax; it’s about managing relationships between objects smartly. This makes every line of code safer, cleaner, and smarter. #Java #OOP #Polymorphism #Upcasting #Downcasting #ClassCastException #InstanceOf #DailyLearning #CodeBetter #ProgrammingJourney #DevLife
To view or add a comment, sign in
-
🚀 DAY 76/150 — CHECKING SUBTREES WITH RECURSION! 🌳 Day 76 of my 150 Days DSA Challenge in Java and today I solved a problem that strengthens my understanding of tree comparison and recursion 💻🧠 📌 Problem Solved: Subtree of Another Tree 📌 LeetCode: #572 📌 Difficulty: Easy–Medium The task is to determine whether one binary tree is a subtree of another binary tree. A subtree must match both structure and node values exactly. 🔹 Approach Used I used a recursive DFS approach: • Traverse each node of the main tree • For every node: Check if the subtree starting at that node is identical to the given tree • Use a helper function to compare two trees: If both nodes are null → true If values differ → false Recursively compare left and right subtrees ⏱ Complexity Time Complexity: O(n × m) (n = nodes in main tree, m = nodes in subtree) Space Complexity: O(h) (recursion stack) 🧠 What I Learned • Tree problems often require combining traversal + comparison • Recursion is powerful for handling hierarchical structures like trees • Breaking the problem into smaller checks simplifies the solution 💡 Key Takeaway This problem taught me how to: Compare two trees efficiently Apply recursion for structural matching Think in terms of subproblems within trees 🌱 Learning Insight As I continue my Binary Tree journey, I’m understanding that: Most tree problems are based on DFS, BFS, or recursion patterns Mastering these basics makes complex tree problems easier ✅ Day 76 completed 🚀 74 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gZNXaW-C 💡 In trees, solving smaller parts correctly leads to the full solution. #DSAChallenge #Java #LeetCode #BinaryTree #Recursion #DFS #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
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