K-th Symbol in Grammar LeetCode Solution

🚀 Solved: LeetCode 779 — K-th Symbol in Grammar This problem turned out to be a perfect example of how one problem can be solved at multiple levels of thinking — from brute force to mathematical optimization. I implemented 5 different approaches to deeply understand the pattern: 🔹 1. Brute Force Build the entire row using string transformation Time/Space: O(2ⁿ) → Not scalable 🔹 2. Iterative (Flip Counting) Traverse upward and count how many times the value flips Time: O(log n), Space: O(1) 🔹 3. Bit Manipulation (Optimized) Key insight: result = parity of set bits in (k - 1) Code: Integer.bitCount(k - 1) % 2 Clean, fast, and interview-ready 🔹 4. Recursive (Top-Down) Find parent and decide flip based on position Builds strong intuition for recursion trees 🔹 5. Tail Recursion Track flips as a parameter (no work after recursion) Helps understand recursion → iteration conversion 💡 Key Insight: Instead of building the entire string, we only track the path from root to the k-th position. 👉 Final realization: Answer = number of right moves (or set bits in k-1) % 2 ⏱ Complexity: Brute Force → O(2ⁿ) Optimized Approaches → O(log n) This problem really strengthened my understanding of: ✔ Recursion vs Tail Recursion ✔ Optimization thinking ✔ Bit manipulation ✔ Converting recursive logic into iterative solutions 🙏 Special thanks to Sir Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the clear and conceptual explanation: https://lnkd.in/dQBtSyxK 📌 LeetCode: https://lnkd.in/d6CKa-BN 📌 GitHub: https://lnkd.in/gnEfmGAg Recursion is not easy — but with consistent practice, patterns start becoming clear. #Java #DSA #LeetCode #Recursion #Algorithms #ProblemSolving #CodingJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories