https://lnkd.in/gmysJzSq Today I solve the classic tree-recursion problem on LeetCode: “Same Tree”. The task was to determine if two binary trees are structurally identical and have the same node values. What I did Handled base cases: if both nodes are nullptr, return true; if one is nullptr and the other isn’t, return false. Recursively compared the left subtrees and right subtrees. Checked the current node values after the recursive calls. Ensured the solution is clean, simple, and efficient in terms of logic. Here’s the core solution snippet: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) return true; if (p == nullptr || q == nullptr) return false; bool leftSame = isSameTree(p->left, q->left); bool rightSame = isSameTree(p->right, q->right); return (p->val == q->val) && leftSame && rightSame; } }; Key Takeaways Recursive tree problems often boil down to base case checks + recursive calls on subtrees + combining results. Clean code is powerful: Fewer lines, clear logic, fewer errors (e.g., mis-using -> vs >). Regularly solving such problems builds strong fundamentals for more complex tree or graph challenges later on. #LeetCode #Cplusplus #TreeAlgorithm #DSA #ProblemSolving #CodingJourney #CleanCode #SoftwareEngineering
Solved "Same Tree" problem on LeetCode using tree recursion
More Relevant Posts
-
https://lnkd.in/gYKr9A3J Today I solved an interesting Binary Tree problem on LeetCode: “Subtree of Another Tree”. The task was to determine whether one binary tree (subRoot) is a subtree of another (root). This problem reinforced the importance of recursion and tree traversal techniques. My Approach: Wrote a helper function isIndentical to check if two trees are exactly the same. In isSubtree, recursively checked for every node in the main tree whether the subtree matches. Carefully handled null cases to avoid runtime errors. Here’s my C++ implementation: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isIndentical(TreeNode* p, TreeNode* q){ if(p == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; return p->val == q->val && isIndentical(p->left, q->left) && isIndentical(p->right, q->right); } bool isSubtree(TreeNode* root, TreeNode* subRoot) { if(root == NULL) return false; if(isIndentical(root, subRoot)) return true; return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); } }; Key Takeaways: Recursion is a powerful tool for tree problems. Always handle null cases carefully to avoid runtime errors. Writing a clean helper function can simplify complex problems. #LeetCode #CPlusPlus #BinaryTree #DSA #ProblemSolving #CodingJourney #TreeAlgorithms #SoftwareEngineering
To view or add a comment, sign in
-
#100DaysCodingChallenge #Day41 Question : #Problem 205 in Leet Code : Isomorphic Strings Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = "foo", t = "bar" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = "paper", t = "title" Output: true Explanation : 🚀 Problem Solved: Isomorphic Strings (Java) Today I solved an interesting problem — checking if two strings are isomorphic. 💡 Problem Understanding Two strings s and t are said to be isomorphic if the characters in s can be replaced to get t, while preserving the order of characters. Every unique character in s must map to a unique character in t. The mapping should be consistent throughout both strings. ✅ Example: s = "egg", t = "add" → Isomorphic (e→a, g→d) s = "foo", t = "bar" → Not Isomorphic s = "paper", t = "title" → Isomorphic 🧠 Approach Explanation To determine if two strings are isomorphic, we need to ensure: Each character in s maps to exactly one character in t. The reverse should also hold true — each character in t maps to only one in s. I divided the logic into two steps: Step 1: Create a mapping from characters of s → t using a HashMap. If a character is already mapped, check if the new mapping remains consistent. If not, the strings are not isomorphic. Step 2: Repeat the process from t → s to ensure the mapping is bijective (one-to-one and onto). Finally, if both mappings are valid, the strings are isomorphic. 🔍 Key Highlights Used a HashMap<Character, Character> to store the character mapping efficiently. Checked both forward and reverse mappings to prevent invalid one-way mappings. Time Complexity → O(n) (single pass over the string). Space Complexity → O(1) (since only character mappings are stored). 🎯 Takeaway This problem strengthened my understanding of hashing, string manipulation, and bijection logic in programming. It also showed how thinking in two directions (s → t and t → s) ensures the correctness of the mapping. #100DaysCodingChallenge #problemsolving #java #Day41 10000 Coders karunakar pusuluri Rudra Sravan kumar Manoj Kumar Reddy Parlapalli
To view or add a comment, sign in
-
-
✨ Today marks Day 7 of my LeetCode streak! I solved a fun and logical problem that reminded me how important simple ideas like arrays and booleans can be in solving tricky questions. 💡 Problem: Find the Two Sneaky Numbers In the town of Digitville, there’s a list called nums that should contain all integers from 0 to n - 1 exactly once. But two numbers decided to appear twice, making the list longer! 😅 My task was to find those two sneaky numbers and bring peace back to Digitville. 📘 Example: Input: nums = [0,3,2,1,3,2] Output: [2,3] Explanation: Numbers 2 and 3 appear twice in the array. 🧠 My Thought Process: At first, I thought of sorting the array and checking adjacent elements, but that would take O(n log n) time. Then I realized I could just keep track of which numbers I’ve seen using a boolean array — whenever I see a number again, that’s one of the sneaky ones! Since n ≤ 100, a simple O(n) solution works perfectly here. 💻 Code (Java): class Solution { public int[] getSneakyNumbers(int[] nums) { int n = nums.length - 2; boolean[] seen = new boolean[n]; int[] result = new int[2]; int idx = 0; for (int num : nums) { if (seen[num]) { result[idx++] = num; if (idx == 2) break; } else { seen[num] = true; } } return result; } } 🔍 Dry Run Example: nums = [0,3,2,1,3,2] Start → seen = [F,F,F,F] See 0 → mark as true See 3 → mark as true See 2 → mark as true See 1 → mark as true See 3 again → duplicate #1 See 2 again → duplicate #2 ✅ Output → [3,2] (order doesn’t matter) ⚙️ Complexity: Time: O(n) Space: O(n) Simple, clean, and efficient! 🎯 Key Learnings: Reinforced how boolean arrays can efficiently handle duplicates. Learned to identify when sorting isn’t needed — sometimes direct logic is faster. Keeping things simple often gives the most elegant solutions. 🗓️ LeetCode Streak: Day 7 / Small Steps → Big Progress 🚀 Each day I’m learning new ways to look at problems — this one taught me simplicity is power 💪 #LeetCode #100DaysOfCode #Java #DSA #ProblemSolving #LearningJourney #CodingPractice #DeveloperLife
To view or add a comment, sign in
-
-
🚀 Day 92/100 of #100DaysOfLeetCode 🚀 🎯 Problem: 2169. Count Operations to Obtain Zero You are given two non-negative integers num1 and num2. In one operation: If num1 >= num2, subtract num2 from num1. Otherwise, subtract num1 from num2. Repeat until either num1 or num2 becomes 0. 🔍 Goal: Find the total number of operations required to make one of them zero. 💡 Brute Force Approach: Simply simulate the subtraction steps using a while loop. int countOperations(int num1, int num2) { int count = 0; while(num1 != 0 && num2 != 0) { if(num1 >= num2) num1 -= num2; else num2 -= num1; count++; } return count; } ⏱️ Time Complexity: O(max(num1, num2)) 💾 Space Complexity: O(1) ⚡ Optimized Approach (Using Modulo): Instead of repeatedly subtracting, we can jump ahead using division & modulo — similar to the Euclidean algorithm for GCD. int countOperations(int num1, int num2) { if (num1 == 0 || num2 == 0) return 0; if (num1 < num2) swap(num1, num2); return num1 / num2 + countOperations(num1 % num2, num2); } 🔹 This optimization uses mathematical insight to skip redundant subtractions. 🔹 Works recursively, reducing both time and iterations drastically. ⏱️ Time Complexity: O(log(max(num1, num2))) 💾 Space Complexity: O(log(max(num1, num2))) (recursive stack) 🧠 Key Learnings: Recognized the pattern resembling the GCD algorithm. Reduced repeated subtraction using division and modulo. Understood base cases where either number becomes zero. ⚠️ Edge Cases to Keep in Mind: If either number starts as 0, return 0. If both numbers are equal, only one operation is needed. Large numbers — ensure no overflow issues in recursion. 🔥 Outcome: Problem Solved ✅ — Efficient, Clean, and Recursive! #100DaysOfCode #LeetCode #Day92 #Cplusplus #CodingChallenge #ProblemSolving #DSA #Algorithms #CodingJourney #LearnWithMe #TechCommunity #SoftwareEngineering #Optimization #CodeNewbie
To view or add a comment, sign in
-
-
#Day10 of #120DaysChallenge User input = Information you (the user) type into a program when it's asking for it during execution. Run-time input = Input given while the program is running, not before it starts. #giving varible values a=7 b=6 print(a+b) #runtime_input or user_input #int #int only accepts int values as inputs a=int(input('enter a value :' )) b=int(input('enter b value :')) print(a+b) #float #float will accept both int and float values as input a=float(input('enter a value :')) b=float(input('enter b value :')) print(a+b) #str a=str(input('enter name of your city :')) print(a) #another type in strings #input() :if we dont declared any data type we gave input it will take like strings in python a=input('enter name :') print(a) #UseCase example fname=input('enter your first name') lname=input('enter your second name') print(fname+''+lname) #complex a=complex(input('enter a value :')) b=complex(input('enter b value :')) print(a+b) #bool #if we done a+b+c it will take like 1 varible in each give 3 a=bool(input('enter a value')) b=bool(input('enter b value')) c=bool(input('enter c value')) print(a+b+c) #UseCase Program for ATM Machine Process a=int(input('enter a value :')) b=int(input('enter b value :')) c=int(input('Choose the options 1.add 2.sub 3.mul')) #here it will accepts all types of data at runtime because string accepts all type of data conversions print(a+b) print(a-b) #to run this operations with numbers we have to use loops after that concept we will do that print(a*c) #UseCase Program for ATM Machine Process to get the add,sub,mul in new lines we have to use it in triple quotes a=int(input('enter a value :')) b=int(input('enter b value :')) c=int(input('''Choose the options 1.add 2.sub 3.mul''')) #here it will accepts all types of data at runtime because string accepts all type of data conversions print(a+b) print(a-b) print(a*c) #using operation names a=int(input('enter a value :')) b=int(input('enter b value :')) c=input('''Choose the options add sub mul''') #here it will accepts all types of data at runtime because string accepts all type of data conversions print(a+b) print(a-b) print(a*c) #withoutusing scripts giving values a=int(input()) b=int(input()) print(a+b) Pooja Chinthakayala mam #day10Challengedone
To view or add a comment, sign in
-
Hi Everyone: #Day-08 Concept: Sets & set methods Today I have learned about set & set methods #Sets: set is an unordered collection of elements enclosed within a curly bracket and separated by commas. 1)set does not stores duplicate values The elements contained in a set must be of immutable type 2)sets are randomly ordered. Ex:>>> a={3, 5.5, 'python', 7+5j, True} >>>type(a) output:<class 'set'> #SetMethods() #issubset a={1,2,3,4,5,6} b={7,8,9,10} a.issubset(b) False a={2,3,4,5,6,7,8} b={6,7,8} b.issubset(a) True #issuperset a={4,5,6,7,8,9} b={7,8,9} a.issuperset(b) True b.issuperset(a) False #add a={10,20,0} a.add(50) a {0, 10, 20, 50} #intersection a={1,2,3,4,5} b={3,4,5,6,7} a.intersection(b) {3, 4, 5} b.intersection(a) {3, 4, 5} #union a={3,4,5,6,7} b={6,7,8,9,10} a.union(b) {3, 4, 5, 6, 7, 8, 9, 10} b.union(a) {3, 4, 5, 6, 7, 8, 9, 10} #update a={3,4,5,6,7} b={6,7,8,9,10} a.update(b) a {3, 4, 5, 6, 7, 8, 9, 10} b.update(a) b {3, 4, 5, 6, 7, 8, 9, 10} #difference a={1,2,3,4,5,6,7} b={3,5,7,9,10,11} a.difference(b) {1, 2, 4, 6} b.difference(a) {9, 10, 11} #intersection_update a={10,11,12,13,14,15} b={12,14,16,17,18} a.intersection_update(b) a {12, 14} b.intersection_update(a) b {12, 14} #symmetric_difference a={2,4,6,8,10,12,14} b={1,3,4,5,8,12,15} a.symmetric_difference(b) {1, 2, 3, 5, 6, 10, 14, 15} a {2, 4, 6, 8, 10, 12, 14} b.symmetric_difference(a) {1, 2, 3, 5, 6, 10, 14, 15} b {1, 3, 4, 5, 8, 12, 15} #symmetric_difference_update a={8,9,10,11,12,13,14,15} b={10,11,13,15,16,17} a.symmetric_difference_update(b) a {8, 9, 12, 14, 16, 17} b.symmetric_difference_update(a) b {8, 9, 10, 11, 12, 13, 14, 15} #pop a.pop() 3 a {4, 5, 6, 7, 8} #remove() a.remove(5) a {4, 6, 7, 8} #copy >>> a={6,7,8,9} >>> a.copy() {8, 9, 6, 7} #clear() >>> a.clear() >>> a set() Thank you Codegnan, Uppugundla Sairam Sir, Pooja Chinthakayala Mam, Saketh Kallepu Sir.
To view or add a comment, sign in
-
LLM Inference: p95 120 ms → 32 ms (−73%) & cost −56%; exact levers below Context: single A100 | 7B chat model | batchy traffic | long prompts. Goal: lower tail latency + cost without quality loss. What I changed (in ROI order): 1️⃣ Continuous batching + paged attention (vLLM/Triton) → Utilization ↑, context swaps cheap, throughput ↑ 2️⃣ FlashAttention + fused kernels → less HBM pressure 3️⃣ Weight-only INT8 / NF4 quantization → smaller KV cache, near-lossless perplexity 4️⃣ Speculative decoding (1.3B draft → 7B target) → tokens/s ↑ by ~2–3× 5️⃣ KV cache reuse + prompt caching → warm prompts = “free” tokens 6️⃣ ONNX / TensorRT graph opt → fused ops, FP16/TF32 where safe 7️⃣ Scheduler tuning → balance max tokens × max batch × wait time Code snippets: # vLLM server pip install vllm python -m vllm.entrypoints.api_server \ --model meta-llama/Llama-2-7b-chat-hf \ --tensor-parallel-size 1 \ --max-num-batched-tokens 8192 \ --enable-prefix-caching \ --gpu-memory-utilization 0.92 # INT8 quantization from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig bnb = BitsAndBytesConfig(load_in_8bit=True) m = AutoModelForCausalLM.from_pretrained(".../7b", quantization_config=bnb, device_map="auto") tok = AutoTokenizer.from_pretrained(".../7b") # Speculative decoding pipe = pipeline("text-generation", model=target_model, draft_model=draft_model) pipe("prompt...", max_new_tokens=128) Results: - p95 latency: 120 ms → 32 ms - Cost per 1M tokens: −56% - Quality (win rate Δ ≈ ±1%) Takeaway: Don’t start with bigger GPUs; start with batching, kernels, quantization, and caching. Then cache everything.
To view or add a comment, sign in
-
-
❌DONT USE string::length() it takes 2ms more than string::size()...... Well that's what I thought when I first observed this execution time difference while optimizing my C++ code. But actually - 🚀 DSA Micro-Insight: std::string::size() vs std::string::length() in C++ 💡 Observation: 1.Both size() and length() return the number of characters in a std::string. 2.Internally, length() simply calls size(). At first glance, one might think: “Ah! length() must be slightly slower because it adds one extra function call.” 💠 How string class looks internally- class basic_string { private: char* _M_data; // Pointer to the actual character array size_t _M_string_length; // Cached length of the string size_t _M_allocated; // Allocated capacity (for dynamic resizing) }; 💠 What string::size() does internally- size_t size() const noexcept { return _M_string_length; } 💠 What string::length() does internally- size_t length() const noexcept { return size(); } 🔍 Reality: 1.Both are O(1) operations — they just read a cached integer from the string object. 2.Modern compilers inline both functions aggressively, so at runtime, length() and size() are essentially identical. 💠 Normally, calling a function involves: 1.Jumping to the function’s memory location. 2.Executing instructions. 3.Returning to the caller. 💠 Inline function If the compiler inlines a function, it replaces the function call with the function body directly at compile time. Example - size_t length() const noexcept { return size(); } After inlining, a call like: auto n = s.length(); becomes (essentially): auto n = s._M_string_length; // direct memory read ⚠️ So why do online platforms like LeetCode sometimes show size() as “faster”? It’s not an algorithmic difference. Tiny variations (1–3 ms) arise from: 1.Compiler inlining decisions on the judge’s server 2.Instruction cache and CPU micro-optimizations 3.Shared server load or measurement granularity 💡 Takeaways for developers & interview prep: 1.Use .size() for loops, STL consistency, and competitive programming. 2.Use .length() for semantic clarity in text-processing contexts. 3.Understand how STL stores data — reading a cached length makes O(1) operations possible, unlike C-style strings (strlen()) which are O(N). 🟡 This micro-observation may seem trivial, but it’s a reminder: True mastery comes from understanding what happens under the hood — something that differentiates a good coder from a great one. #DSA #CodingTips #ProgrammingInsights #CompetitiveProgramming #Performance #SoftwareEngineering #Optimizations
To view or add a comment, sign in
-
-
I’ve released pytoon-codec, a small Python library that implements a TOON (Token-Oriented Object Notation) encoder/decoder for time series and nested event logs. The motivation is simple: a lot of LLM pipelines move structured data around as JSON, but TOON-style tabular blocks can be significantly more token-efficient while staying easy to read and post-process. The codec is opinionated towards common telemetry-style workloads. Time series are encoded as compact TOON tables (e.g. `metrics[1000]{ts,value}: …`), and nested event payloads are flattened into dotted column names (such as `payload.sensor`, `payload.room`, `user.id`). On the way back, the library can expand those dotted paths into nested dicts again, so your application code still works with normal Python structures. Unsupported shapes (like arrays nested deep inside objects) fail loudly with clear errors rather than silently degrading. You can find the project at: https://lnkd.in/d4EStR9C. If you’re experimenting with TOON for LLM prompts around metrics, logs, or sensor data, I’d be very interested in feedback, bug reports, and examples of how you’re using it.
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