🚀 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
K-th Symbol in Grammar LeetCode Solution
More Relevant Posts
-
🚀 Efficient Duplicate Detection with Hash Sets | LeetCode Today, I tackled the Contains Duplicate problem. While the brute force approach is often the first instinct, optimizing for time complexity is where the real fun begins! 💡 The Problem: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. ⚡ My Approach: I utilized a Hash Set to track elements as I traversed the array. This allows for near-instantaneous lookups compared to nested loops. 👉 The Logic: Initialize an empty set seen. Iterate through the array once. For each number, check: "Have I seen this before?" (Is it in the set?) If Yes → Return True immediately. If No → Add the number to the set and keep moving. 🔥 Complexity Analysis: ⏱ Time Complexity: $O(n)$ – We only pass through the list once. 📦 Space Complexity: $O(n)$ – In the worst case (all unique elements), we store all $n$ elements in the set. 🏆 The Result: ✔️ Accepted: All 77 test cases passed. ✔️ Performance: 9 ms runtime, beating 73.44% of Python3 submissions! 📌 Key Takeaway: Using a Set turns a potential $O(n^2)$ search into a sleek $O(n)$ operation. Choosing the right data structure isn't just about passing tests; it's about writing scalable, "production-ready" code. 💻 Tech Stack: #Python | #DataStructures | #Algorithms #leetcode #dsa #coding #programming #softwareengineering #100DaysOfCode #pythonprogramming #tech #growthmindset
To view or add a comment, sign in
-
-
Some problems don’t just test implementation -- they test how well you recognize patterns under the surface. This week’s practice was a mix of such problems, where the brute force approach is usually obvious, but the real challenge is optimizing it. Here’s a structured breakdown: 🔹 Combinatorics & Mathematical Patterns • Pascal’s Triangle 👉 A good reminder that not all problems need heavy computation -- sometimes understanding the mathematical relationship is enough. 🔹 Extended Majority Problems • Majority Element II (> n/3 times) 👉 Builds on Boyer-Moore Voting, but requires handling multiple candidates - a nice extension of a classic idea. 🔹 k-Sum Pattern (Generalization) • 3 Sum • 4 Sum 👉 These problems highlight a scalable approach: • Sort the array • Fix elements • Use two pointers for the remaining search Once understood, this pattern extends to k-sum problems in general. 🔹 Prefix XOR / Hashing Insight • Count subarrays with given XOR = K 👉 Similar to prefix sum, but with XOR properties. 🔹 Interval Problems • Merge Overlapping Intervals 👉 Sorting + linear traversal is often enough - recognizing overlap conditions is key. 🔹 In-place Merging Techniques • Merge two sorted arrays without extra space 👉 Challenges the usual merge process by forcing O(1) space - pointer-based strategies. 🔹 Array Integrity Problems • Find repeating and missing number 👉 Can be solved using math, hashing - multiple approaches with different trade-offs. 🔹 Divide & Conquer Applications • Count inversions • Count reverse pairs 👉 A great example of how merge sort can be extended beyond sorting to count relationships efficiently in O(n log n). 🔹 Subarray Optimization (Advanced) • Maximum product subarray 👉 Unlike sum problems, product introduces sign complexity - tracking both prefix and suffix product becomes necessary. 💡 Key takeaway: At this stage, many problems are not new - they are variations or extensions of core ideas: • Two pointers (k-sum) • Prefix techniques (sum/XOR) • Merge sort adaptations • Greedy + state tracking 👉 The difference comes from how well you adapt known patterns to slightly unfamiliar constraints. #DSA #Arrays #ProblemSolving #Java #LearningInPublic #Algorithms #SoftwareEngineering #SoftwareDevelopment
To view or add a comment, sign in
-
Shallow Copy vs Deep Copy — The 2 AM Bug Trap 🛑 Most developers think they understand copying objects, until their original data mysteriously changes. That’s not a bug, that’s memory behavior biting you. → Shallow Copy Creates a new container, but nested objects are still shared (by reference) 👉 Change nested data → both copies change. Best for: Flat, simple data. → Deep Copy Creates a completely independent clone, everything is copied recursively. 👉 Change anything → original stays untouched Best for: Complex, nested structures. 💡 Rule of Thumb Shallow → when you only need a surface-level copy Deep → when you need true isolation ⚠️ The real trap: Most bugs aren’t syntax errors. They come from not understanding how data behaves in memory. If you’ve ever spent hours debugging only to realize it was a shallow copy issue. Welcome to the club 😄 #Python #Python3 #Programming #SoftwareEngineering #CleanCode #Debugging #TechTips #PythonDeveloper #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Solved LeetCode 110 – Balanced Binary Tree 🌳 Most people start with a brute-force approach (recomputing heights again and again), which leads to O(n²) in worst cases. Instead, I focused on an optimized bottom-up DFS (post-order traversal). 💡 Key idea: Each node returns its height if balanced Returns -1 as a sentinel if unbalanced Propagates early to avoid unnecessary computation class Solution { public boolean isBalanced(TreeNode root) { return checkHeight(root) != -1; } int checkHeight(TreeNode node){ if (node == null) return 0; int left = checkHeight(node.left); int right = checkHeight(node.right); if (left == -1 || right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } } 🚀 Complexity: Time: O(n) Space: O(h) (recursion stack) 📌 What I learned: Combining multiple computations (height + balance) into a single traversal Using sentinel values to simplify recursion Thinking in bottom-up patterns for tree problems This pattern is widely useful in tree-based problems and even shows up in backend systems where hierarchical data needs validation. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
-
I recently dug into the open-sourced code powering X’s timeline. How do they filter millions of global posts in milliseconds? Here is the TL;DR on their backend: 𝗭𝗲𝗿𝗼 𝗛𝗮𝗻𝗱-𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗲𝗱 𝗥𝘂𝗹𝗲𝘀: X ripped out manual heuristics. Relevance is now entirely decided by a Grok-based Transformer predicting exact engagement probabilities: 𝘗(𝘓𝘪𝘬𝘦), 𝘗(𝘙𝘦𝘱𝘭𝘺), 𝘗(𝘙𝘦𝘱𝘰𝘳𝘵). 𝗧𝘄𝗼-𝗣𝗿𝗼𝗻𝗴𝗲𝗱 𝗦𝗼𝘂𝗿𝗰𝗶𝗻𝗴: The feed blends two distinct systems in parallel: • 𝗧𝗵𝘂𝗻𝗱𝗲𝗿: A blazingly fast, in-memory Rust datastore serving real-time posts from people you follow. • 𝗣𝗵𝗼𝗲𝗻𝗶𝘅: An ML "Two-Tower" model retrieving viral, out-of-network content. "𝗖𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲 𝗜𝘀𝗼𝗹𝗮𝘁𝗶𝗼𝗻": A brilliant ML design trick. During ranking, posts are masked so they can't "see" each other. This means a post's score is absolute for you, making the results highly cacheable. 𝗥𝘂𝘀𝘁 + 𝗝𝗔𝗫: The ultimate high-scale stack. Rust handles the brutal concurrent orchestration (home-mixer), while Python/JAX powers the ML heavy lifting. It’s a masterclass in dropping traditional database lookups and pushing pure ML inference to the edge. Has anyone else here successfully moved away from manual feature rules to pure ML ranking? Let’s chat below! #SystemDesign #MachineLearning #Rust #SoftwareEngineering #Architecture
To view or add a comment, sign in
-
-
Your code works. But why is it suddenly slow in production? 🤯 Most developers don’t fail because of syntax. They fail because they ignore time complexity 👇 Today’s Concept: Time Complexity (Big O) Same output. Different performance. # O(n) → Linear Search numbers = [10, 20, 30, 40, 50] for num in numbers: if num == 40: print("Found ✅") break Works well for small data. But gets slower as data grows. --- # O(1) → Dictionary Lookup data = { "name": "John", "role": "Developer" } print(data["role"]) Fast and efficient ⚡ Because lookup is constant time. --- The golden rule: Not all working code is good code. Ask: - How fast will this run? - What happens with 1 million rows? - Can this be optimized? --- Smart developers think like this: First → Make it work Then → Make it clean Finally → Make it fast 🔥 Master Big O → you stop writing code that breaks under pressure. #Python #AdvancedPython #BigO #TimeComplexity #CodingJourney #LearnInPublic #100DaysOfCode #SoftwareEngineering #TechSkills #DeveloperLife
To view or add a comment, sign in
-
Update on my Photo Retrieval Project 🚀 The project is starting to take real shape. In this phase, I implemented a vector database and learned how to perform basic CRUD operations on embeddings. One challenge I noticed was that most of the code was initially AI-generated, which created a disconnect in understanding. To address this, I spent time cleaning up the codebase—simplifying logic, removing unnecessary parts, and restructuring it in a way that made sense to me. This cleanup phase was valuable. It helped me better understand Python, regain ownership of the project, and apply my own methodology. Instead of leaving cleanup for the end, doing it iteratively made the process smoother and easier to manage. Key updates in this phase: • Improved indexing script — now processes only new images and updates embeddings incrementally, avoiding full recomputation • Integrated a vector database for efficient similarity search • Built a REST API using Flask to fetch images matching a query • Added a file-serving route to return images by filename • Refactored the codebase to support real-world datasets instead of being tightly coupled to CIFAR-10 While the system is now capable of handling real-world data, I’m still using the CIFAR dataset for testing. This phase was less about building new features and more about understanding, refining, and making the system scalable. More updates soon. If you’d like to follow along, here’s the repo: https://lnkd.in/dUEzpxX8
To view or add a comment, sign in
-
Andrej Karpathy asked for a tool that turns any folder into a queryable knowledge graph. Graphify appeared 48 hours later. 4K stars. I built the same thing two months earlier. DeadReckoning was a winner in the LangChain × SurrealDB hackathon in London doing exactly this - parsing a Python codebase into a knowledge graph you can query in plain English. What depends on this function? What changed between versions? Is anything undocumented? But here’s what I find interesting: I solved the problem completely differently. Graphify uses tree-sitter AST parsing + Claude subagents + a file-based graph with Louvain clustering. It’s a skill you install in Claude Code. Designed to be fast and zero-config. DeadReckoning uses SurrealDB as a live database storing the graph, vectors, agent state, and version history in one instance. Hybrid search with Reciprocal Rank Fusion inside the database. LangGraph agents with human-in-the-loop interrupts and durable checkpoints. Function-level versioning using Docker-style change detection. Two approaches to the same problem. Graphify optimises for speed and simplicity. DeadReckoning optimises for depth - multi-hop traversal, version-aware diffing, and autonomous multi-tool agent chains. The fact that Karpathy independently validated the problem space is what matters. Knowledge graphs for codebases aren’t a novelty project - they’re becoming infrastructure. Repo in the comments.
To view or add a comment, sign in
-
-
🚨 34 RAG techniques in one practical guide every Al developer should save today. ➡️A guidebook that breaks down **34 real RAG techniques** with Python examples, pros, cons, and use cases. If you are building Al apps, copilots, internal search, or support bots, this is worth your time. 1. Foundations (Start Here) *Basic RAG *Reliable RAG *RAG with CSV Files *Optimizing Chunk Sizes *Proposition Chunking 2. Better Queries & Better Context *Query Transformations *HYDE *HYPE *Contextual Chunk Headers *Semantic Chunking 3. Smarter Retrieval Layer *Fusion Retrieval * Reranking *Ensemble Retrieval *Hierarchical Indices *Multi-faceted Filtering 4. Long Context Efficiency *Relevant Segment Extraction * Context Window Enhancement *Contextual Compression * Document Augmentation * Dartboard Retrieval 5. Agentic & Iterative Systems * Agentic RAG with Contextual Al *Adaptive Retrieval *Iterative Retrieval *Retrieval with Feedback Loop * Sophisticated Controllable Agent 6. Advanced Architectures *Graph RAG with LangChain * Microsoft GraphRAG *RAPTOR * Self-RAG *Corrective RAG (CRAG) 7. Evaluation & Trust *DeepEval *GroUSE *Explainable Retrieval My biggest takeaway: Most teams stop at Basic RAG. The real gains come from retrieval quality, reranking, evaluation, and feedback loops. That is where production systems win.
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
Awesome :)