🚀 Day 75 / 100 Days of Code 🌳 Problem: Check if a Binary Tree is Univalue A tree is univalue if all nodes contain the same value. ✅ My Approach Recursively check both left and right subtree If a node doesn't match the root value → return false Base case: null nodes naturally return true Result: 0 ms runtime, beating 100% submissions 🚀 💡 Takeaway Recursion really shines when validating conditions across tree structures. 🧩 Tech Stack: Java </> Algorithm | Recursion | Trees #100DaysOfCode #LeetCode #Java #DataStructures #CodingJourney #ProblemSolving #LinkedList
"Day 75: Checking Univalue Binary Tree with Java Recursion"
More Relevant Posts
-
✨ Day 19 - Quick Sort Implementation in Java (User Input Version) Continuing my DSA journey with one of the most important and interview-relevant sorting algorithms — Quick Sort. Instead of using built-in sorting utilities, I implemented Quick Sort from scratch to clearly understand how partitioning and recursion work under the hood. 🧠 What I Did Took array size and elements as user input Chose the last element as pivot (Lomuto partition) Rearranged elements around the pivot Recursively sorted left and right subarrays Printed both unsorted and sorted arrays for clarity 💡 Concepts Strengthened Divide and Conquer strategy Recursion flow and base conditions Pivot selection and partition logic In-place sorting (no extra arrays) Time complexity trade-offs in algorithms 📌 Why This Matters Quick Sort is widely used due to its average-case efficiency and forms the foundation for understanding advanced sorting and optimization techniques. Writing it manually forces you to think logically instead of memorizing patterns. Step by step. Logic over shortcuts. 🚀 #DSA #Java #QuickSort #SortingAlgorithms #ProblemSolving #CodingJourney #LearnEveryday #DataStructures #TechJourney #DataStructureAndAlgorithm
To view or add a comment, sign in
-
-
Problem 2: Binary Tree Paths Level: Easy–Medium Platform: LeetCode 257 Return all root-to-leaf paths as strings like: Copy code "1->2->5" "1->3" 🔹 Java Code import java.util.*; class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<>(); if (root == null) return result; dfs(root, "", result); return result; } private void dfs(TreeNode node, String path, List<String> result) { if (node == null) return; // add current node to path path = path + node.val; // leaf -> store path if (node.left == null && node.right == null) { result.add(path); return; } // continue path with "->" path = path + "->"; dfs(node.left, path, result); dfs(node.right, path, result); } } 🔹 Explanation Build path as a string while traversing When leaf reached → store full path No backtracking needed because we use new string each recursion call Time: O(n × path-length) Space: O(h) recursion #DSA #DataStructuresAndAlgorithms #Coding #Programmer #LeetCode #CodeEveryday #JavaDSA #CodingPractice #ProblemSolving #CP #CompetitiveProgramming #DailyCoding #TechJourney #CodingCommunity #DeveloperLife #100DaysOfCode #CodeWithMe #LearnToCode #GeekForGeeks #CodingMotivation
To view or add a comment, sign in
-
Most Java developers ignore BitSet. And that’s a mistake. Because BitSet is one of the cleanest ways to unlock serious memory optimization in Java. Instead of storing data as booleans, integers, or objects… BitSet stores a single bit per value. Let that sink in. • boolean[] → ~1 byte per value • BitSet → 1 bit per value That’s 8x less memory — instantly. But memory is just the beginning. What makes BitSet powerful: • Ultra-fast and, or, xor (CPU-level bit operations) • Minimal object allocation → less GC pressure • Perfect for large-scale flags & state tracking Real-world use cases: • Feature flags at scale • Permission systems • Tracking active users • Caching & bloom filters • Graph and algorithm-heavy systems The real lesson here 👇 Performance isn’t always about complex algorithms. Sometimes, it’s about choosing the right data structure. If you haven’t explored BitSet yet — add it to your Java toolbox. Have you ever used BitSet in production? Or is it still flying under your radar? #Java #BitSet #Performance #MemoryOptimization #BackendEngineering #DataStructures #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
LeetCode #704 – Binary Search Solved this fundamental array + searching problem in Java. 🔍 Core Logic : Binary search works only on a sorted array. Initialize two pointers : left = 0, right = nums.length - 1 While the search space is valid (left <= right) Calculate mid safely mid = left + (right - left) / 2 Compare: If nums[mid] == target → return index If nums[mid] < target → move right → left = mid + 1 Else → move left → right = mid - 1 If search space becomes empty → return -1 💡 Key Insight Each comparison eliminates half of the array, which is why binary search is extremely efficient. ⚙️ Complexity Time: O(log n) Space: O(1) ✔ All test cases passed 🚀 Clean, efficient, and interview-ready solution #LeetCode #LeetCode704 #BinarySearch #Java #DataStructures #Algorithms #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
-
Mastering DSA with Java — Recursion (Part 2) Recursion is starting to feel less scary and more logical. Today’s focus was on problems where you stop thinking in loops and start trusting the call stack. Each problem forced me to think about base cases, recursive flow, and return paths instead of step-by-step execution. Here’s what I practiced today: 🔹 Find Last Occurrence in an Array — recursion with backtracking 🔹 Print Xⁿ — optimized power using divide & conquer 🔹 Fibonacci Series — classic recursion (and why it’s expensive) 🔹 Check if an Array is Sorted — recursion as a verifier, not a builder ⸻ 💡 What recursion is teaching me (the hard but useful way): ✨ Base case is everything — miss it and you crash ✨ Recursion works backward, not forward ✨ Some problems look simple but hide exponential costs ✨ Optimization (like reducing calls) matters early ✨ DSA is less about syntax, more about thinking patterns ⸻ This is Part 2 of recursion. #DSA #Java #Recursion #ProblemSolving #LearnInPublic #CodingJourney #JavaDeveloper #DataStructures
To view or add a comment, sign in
-
🌳 Problem 2: Path Sum II (Return All Paths) Level: Medium Platform: LeetCode 113 Now instead of boolean, we must collect all valid paths. 🔹 Java Code import java.util.*; class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>(); dfs(root, targetSum, path, result); return result; } private void dfs(TreeNode node, int sum, List<Integer> path, List<List<Integer>> result) { if (node == null) return; path.add(node.val); // choose // Leaf node — check sum if (node.left == null && node.right == null && sum == node.val) { result.add(new ArrayList<>(path)); // store copy } else { dfs(node.left, sum - node.val, path, result); dfs(node.right, sum - node.val, path, result); } path.remove(path.size() - 1); // backtrack } } 🔹 Explanation (Backtracking) Add node to current path If leaf + sum matched → store copy of path After exploring children → remove last element (so path stays correct for siblings) Time: O(n) Space: O(h) recursion + path storage #DSA #DataStructuresAndAlgorithms #Coding #Programmer #LeetCode #CodeEveryday #JavaDSA #CodingPractice #ProblemSolving #CP #CompetitiveProgramming #DailyCoding #TechJourney #CodingCommunity #DeveloperLife #100DaysOfCode #CodeWithMe #LearnToCode #GeekForGeeks #CodingMotivation
To view or add a comment, sign in
-
Mastering DSA with Java — Recursion (Part 3 | Advanced) Today was a big leap in my recursion journey — moving from understanding recursion to actually thinking recursively. This part focused on classic problems that force you to see patterns, choices, and overlapping subproblems clearly. Here’s what I worked on today: 🔹 Remove Duplicate Characters from a String Using recursion + a boolean map to track visited characters. 🔹 Tiling Problem Counting the number of ways to tile a 2×n board — pure recursion logic that mirrors Fibonacci-style thinking. 🔹 Friends Pairing Problem Understanding choices: stay single or pair up — and how recursive relations emerge naturally. 🔹 Print Binary Strings Generating all valid binary strings without consecutive 1s — a great example of constraints in recursion. ⸻ 💡 What this part really taught me Recursion isn’t about memorizing code — it’s about: Breaking problems into choices Trusting the function call Defining clear base cases Thinking in terms of subproblems, not loops #DSA #Java #Recursion #ProblemSolving #LearnInPublic #CodingJourney #JavaDeveloper #DataStructures
To view or add a comment, sign in
-
Day 95/100 – #100DaysOfCode 🚀 | #Java #HashMap #Randomization ✅ Problem Solved: Random Flip Matrix (LeetCode 519) 🧩 Problem Summary: You are given a binary matrix initialized with all 0s. Each call to flip() should randomly return the position of a 0 and change it to 1. No position should be flipped more than once until reset() is called. 💡 Approach Used: ✔ Used HashMap + Randomization to simulate shuffling ✔ Treat the matrix as a flattened 1D array Steps: Map each index to its actual value using a HashMap Randomly pick an index from the remaining unflipped range Swap it with the last available index Decrease the available range On reset(), clear the map and restore the range ⚙ Time Complexity: O(1) per flip() 📦 Space Complexity: O(K) (where K = number of flipped cells) ✨ Takeaway: This problem is a great example of achieving uniform randomness without storing the entire matrix — smart indexing beats brute force. #Java #LeetCode #HashMap #Randomization #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
#Day-105) LeetCode Problem #944: Delete Columns to Make Sorted ✨ Today I solved an interesting problem that checks whether columns in a grid of strings are lexicographically sorted. If not, we count how many need to be deleted. 🔹 Approach: Iterate column by column Compare characters row by row Increment count if any column is unsorted 💻 Java Solution: (Attached in the image 👇) 🔑 Takeaway: This problem reinforces the importance of string manipulation and nested iteration logic. Even simple-looking problems can sharpen our ability to think in terms of grids and constraints. #LeetCode #Java #ProblemSolving #CodingChallenge #MERN #BackendDevelopment #LearningEveryday
To view or add a comment, sign in
-
-
⚠️ Lambdas Are NOT Shorter Anonymous Classes Most Java developers think lambdas are just syntax sugar. They’re not. The JVM treats them very differently 👇 🔸Anonymous Class Greeting g = new Greeting() { public void sayHello(String name) { System.out.println("Hello " + name); } }; What the compiler does: → Generates a new .class file (YourClass$1.class) → Creates a synthetic constructor → Copies captured variables into fields → Always creates a new instance → Always captures the enclosing class That’s why variables must be effectively final. ⚡Lambda Expression Greeting g = name -> System.out.println("Hello " + name); What actually happens: → No .class file generated → Compiler emits invokedynamic → JVM links the lambda at runtime → Uses LambdaMetafactory → May reuse instances when stateless Lambdas are runtime-bound, not compile-time types. Why This Matters in Production → Lower memory overhead → Better garbage collection → JVM-level optimizations → Faster execution in hot paths 📎 I’ve attached a document with a deep dive into bytecode, memory, and performance differences. Save this if it changed how you think about Java. #Java #JVM #JavaDeveloper #BackendDevelopment #SoftwareEngineering #Programming #CleanCode #JavaInternals #LambdaExpression #AnonymousClass
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