🚀 Top View of a Binary Tree in Java | BFS + HashMap Approach Today I implemented an efficient solution to find the Top View of a Binary Tree using Java. This approach uses Breadth-First Search (BFS) along with a HashMap to track the first node encountered at each horizontal distance. 🔍 Key Concepts Used: Queue (BFS) to traverse level-wise HashMap to store the first node at each horizontal distance Tracking minimum and maximum distances to print the result in order 💡 Why this works: The first node encountered at each horizontal distance from the root represents the top view, and BFS ensures we visit nodes level by level. 🧠 Code Snippet: class Solution { class Pair{ Node node; int dist; Pair(Node node , int dist){ this.node = node; this.dist = dist; } } public ArrayList<Integer> topView(Node root) { ArrayList<Integer> ans = new ArrayList<>(); HashMap<Integer,Integer> mp = new HashMap<>(); Queue<Pair> q = new LinkedList<>(); q.add(new Pair(root,0)); int minDist = Integer.MAX_VALUE , maxDist = Integer.MIN_VALUE; while(!q.isEmpty()){ Pair front = q.remove(); Node node = front.node; int dist = front.dist; minDist = Math.min(minDist,dist); maxDist = Math.max(maxDist,dist); if(!mp.containsKey(dist)) mp.put(dist,node.data); if(node.left!=null) q.add(new Pair(node.left,dist-1)); if(node.right!=null) q.add(new Pair(node.right,dist+1)); } for(int i=minDist;i<=maxDist;i++){ ans.add(mp.get(i)); } return ans; } } 📌 Use Cases: Tree visualization problems Competitive programming Coding interviews 💬 Let me know if you’d like the bottom view, left view, or right view versions too! #Java #DataStructures #BinaryTree #Algorithms #Coding #BFS #InterviewPreparation #ComputerScience #DSA
Java Binary Tree Top View with BFS and HashMap
More Relevant Posts
-
Day 16: VarArgs and Recursion 🔸Variable Arguments (Varargs): A function with varargs can be created in Java using the following syntax: public static void foo(int... arr) { // arr is available here as int[] arr } foo can be called with zero or more arguments, like this: foo(7) foo(7, 8, 9) foo(1, 2, 7, 8, 9) We can also create a function bar like this: public static void bar(int a, int... arr) { // code } bar(1) bar(1, 2) bar(1, 7, 9, 11) 🔸Example static int avg(int... arr) { int result = 0; int avg = 0; for (int element : arr) { result += element; } avg = result / arr.length; return avg; } public static void main(String[] args) { System.out.println("The average is " + avg(3, 5, 8, 7)); } 🔸Recursion A function in Java can call itself. Such calling of a function by itself is called recursion. 🔸Syntax of Recursion in Java: returnType functionName(parameters) { if(base_condition) { return value; } else { return functionName(smaller_problem); } } 🔸Example: Factorial Using Recursion: static int factorial(int n) { if(n == 0 || n == 1) // base condition return 1; else return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println(result); } #Java #Programming #SoftwareDevelopment #JavaDeveloper #Coding #ProblemSolving #LearningJourney #ComputerScience #KodNest
To view or add a comment, sign in
-
-
🚀 Day 113 | Java Logical Program ++>> Check Whether an Array Is Sorted or Not Hello coders👋, Today I worked on a simple but very important array logic problem in Java. The task is to check whether an array is sorted in ascending order or not. ------------------------------------------------------------------------------------------- 💡 Code -----------> public class ArraySortedOrNot { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5, 6}; boolean sorted = true; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { sorted = false; break; } } System.out.println(sorted ? "Sorted Array" : "Not Sorted Array"); } } ------------------------------------------------------------------------------------------- 🖥️ Output --------------> Sorted Array 🔍 Output Explanation The loop compares current element with the next element If any element is greater than the next one → array is not sorted If the loop completes without breaking → array is sorted 📌 Important Concept Array traversal Comparison of adjacent elements Boolean flag usage Early exit using break ⚠️ Important Tip This logic works in O(n) time, which is efficient and recommended for large arrays 🚀 🤔 Engagement How would you check if the array is sorted in descending order? 🤔 👉 CTA If you’re learning Java logic step by step, let’s connect and grow together 🤝💙 #Java #CoreJava #ArrayProgramming #LogicalThinking #JavaDeveloper #CodingJourney #100DaysOfCode #LearnJava #day113 #codewithyuvi
To view or add a comment, sign in
-
-
Java Array A data structure that stores multiple values of the same data type in a single variable. Arrays Class A utility class in Java that provides methods to perform operations on arrays such as sorting and searching. String A class used to represent a sequence of characters in Java; String objects are immutable. String Methods Predefined methods used to manipulate and retrieve information from String objects. StringBuffer and StringBuilder Classes used to create mutable strings; StringBuffer is thread-safe, while StringBuilder is faster but not thread-safe. Immutable and Mutable Immutable objects cannot be changed after creation, while mutable objects can be modified. Exception Handling A mechanism to handle runtime errors and maintain the normal flow of program execution. Shallow Copy and Deep Copy Shallow copy copies object references, while deep copy creates a new independent object. File Handling A process of creating, reading, writing, and deleting files in Java. Multithreading A feature that allows multiple threads to execute concurrently within a program. Synchronization A mechanism used to control access to shared resources in a multithreaded environment. Interthread Communication A technique that allows threads to communicate with each other during execution. Deadlock A situation where two or more threads wait indefinitely for each other’s resources. Daemon Thread A background thread that runs to support user threads and terminates when they finish. Inner Class A class defined inside another class to logically group related classes. Object Class The root superclass of all Java classes from which every class implicitly inherits. pdf Link :- https://lnkd.in/gXEWSAJ2 #Java #CoreJava #JavaDeveloper #JavaInterview #ProgrammingBasics #SoftwareDevelopment #LearnJava #StudentDeveloper #TechLearning
To view or add a comment, sign in
-
-
Why Java Is Not a Pure Object-Oriented Language A pure object-oriented programming language is one where everything in the program is treated as an object. In such languages, even basic values like numbers, characters, and boolean values are represented as objects. There are no primitive data types. javava is a language that embraces many object-oriented concepts, yet it does not fully qualify as a purely object-oriented language. Here are the key reasons why: 1. Presence of Primitive Data Types Java includes several primitive data types, such as: - int - float - double - char - boolean - long - short - byte These types are not objects, which contradicts the principle that all values in a program should be objects. For example, in the code snippet below, `a` is a primitive value, not an object: ```java int a = 5; System.out.println(a); ``` In contrast, languages like Smalltalk treat even numbers and boolean values as objects. 2. Use of the static Keyword Java permits the declaration of methods and variables using the static keyword. Static members are associated with the class itself rather than with an instance of the class, allowing access without creating an object. This undermines the principle that all operations should occur through objects. For instance: ```java class Test { static int count = 0; static void show() { System.out.println("Hello"); } } ``` In this example, the method `show()` can be called without instantiating an object. 3. Wrapper Classes and Primitive Conversion Java offers wrapper classes such as: - Integer - Float - Double - Character - Boolean These classes enable primitive values to be treated as objects. However, Java still relies on primitive types through mechanisms like autoboxing and unboxing. For example: ```java public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: " + k); } } ``` In this case, primitive values #ProgrammingConcepts #SoftwareEngineering #Coding #BackendDevelopment #JavaInterview #TechLearning #ProgrammingEducation #CodeNewbie #DeveloperLife #ComputerScience #ProgrammingTips #JavaConcepts
To view or add a comment, sign in
-
-
Day 25 of Sharing What I’ve Learned 🚀 Method Overloading in Java — Compile-Time Polymorphism Explained 🔥 When building real-world applications, flexibility in handling different inputs is essential… That’s where method overloading becomes powerful 💡 🔹 What Is Method Overloading? Method overloading is the process of defining multiple methods with the same name within the same class, but with different parameter lists. ✔ Same method name ✔ Different number or type of parameters ✔ Improves readability and usability 🔹 Simple Example — Calculator Add Method class Calculator { void add(int a, int b) { System.out.println(a + b); } void add(float a, float b) { System.out.println(a + b); } void add(int a, int b, int c) { System.out.println(a + b + c); } } Now you can call: calc.add(10, 20); calc.add(10.5f, 20.3f); calc.add(5, 6, 7); Same method name ➜ Different behavior ✔ 🔹 How Java Chooses the Correct Method The Java compiler follows 3 rules: 1️⃣ Method name 2️⃣ Number of parameters 3️⃣ Type of parameters This decision happens at compile time, not runtime. 👉 That’s why method overloading is called: ✔ Compile-time polymorphism ✔ Static binding ✔ Early binding ✔ (Also known as false polymorphism) 🔹 Type Promotion If an exact match isn’t found, Java promotes types to the closest compatible one. Example: void add(float a, float b) { } Calling: add(10, 20); ➡ int values are promoted to float ✔ 🔹 Ambiguity Problem Sometimes the compiler can’t decide which method to call ❌ void add(int a, float b) { } void add(float a, int b) { } add(10, 20); // ❌ ambiguous Both methods are equally valid ➜ Compile-time error 🧠 Key Takeaways ✔ Multiple methods can share the same name (within the same class) ✔ Differentiation is based on parameters, not return type ✔ Resolved at compile time ✔ Supports cleaner and more intuitive APIs ✔ Widely used in real-world Java libraries Method overloading makes code easier to use, easier to read, and more flexible — a fundamental concept for interviews and production code. #Java #CoreJava #MethodOverloading #Polymorphism #OOP #Programming #BackendDevelopment #InterviewPreparation #Day25 Grateful for the guidance from Sharath R, Harshit T, TAP Academy
To view or add a comment, sign in
-
-
🚀 Day 19 – Core Java | Arrays (1D, 2D, 3D) + Length Property Deep Dive Today’s session was not just about writing arrays — it was about understanding how arrays behave internally in memory. 🔑 What We Revised ✔ Arrays are objects in Java ✔ Stored in Heap memory ✔ Hold homogeneous data ✔ Index always starts from 0 📌 1D Array – Execution Clarity int[] a = new int[5]; Default values → 0 Access using a[index] Traversal using loop We reinforced: Why loops are mandatory Why System.out.println(a); prints reference, not elements Why traversal logic never changes in 90% of problems 📌 Important Concept: length Property Instead of hardcoding: for(int i = 0; i < 5; i++) We used: for(int i = 0; i < a.length; i++) Why? Because: If array size changes → code still works Makes program dynamic Prevents logical bugs 📌 2D Array – Internal Understanding int[][] a = new int[2][5]; Meaning: 2 Rows 5 Columns per row Key Insight: a.length → number of rows a[i].length → number of columns in row i Traversal Pattern: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + " "); } } Exactly like pattern programming logic. 📌 3D Array – Block, Row, Column int[][][] a = new int[2][3][5]; Think in hierarchy: Block → School Row → Classroom Column → Student Length usage: a.length → number of blocks a[i].length → rows in block a[i][j].length → columns in that row 🧠 Major Takeaways ✔ Hardcoding loop limits is a mistake ✔ length property makes code scalable ✔ Traversal logic remains same across dimensions ✔ Interviewers test syntax + clarity Most students understand arrays. Very few understand how length adapts dynamically. That difference matters in interviews. Strong fundamentals → Fewer bugs → Better problem-solving → Better offers 🚀 #Day19 #CoreJava #Arrays #JavaProgramming #LengthProperty #DataStructures #InterviewPreparation #DeveloperGrowth
To view or add a comment, sign in
-
🚀 Day 14/30 – Java DSA Challenge 🔎 Problem 64: 1614. Maximum Nesting Depth of the Parentheses (LeetCode – Easy) Continuing Day 14 with another fundamental problem focused on Stack usage and Parentheses Processing, which is a very common interview pattern. 🧠 Problem Summary Given a valid parentheses string, the task is to determine the maximum nesting depth. 👉 Nesting depth represents how many parentheses are open simultaneously at any point. Example: (1+(2*3)+((8)/4))+1 Here, digit 8 lies inside 3 nested parentheses, so the answer is 3. 💡 Key Insight Every time we encounter: "(" → Depth increases ")" → Depth decreases So, tracking currently open parentheses helps us determine the maximum depth reached during traversal. A Stack naturally models this behavior. 🔄 Approach Used 1️⃣ Traverse the string character by character 2️⃣ Push '(' into stack when opening bracket appears 3️⃣ Pop when closing bracket appears 4️⃣ Track maximum stack size during traversal 5️⃣ Maximum stack size = Maximum nesting depth ⏱ Complexity Analysis Time Complexity: 👉 O(N) — Single traversal of string Space Complexity: 👉 O(N) — Stack storage in worst case 📌 Concepts Strengthened ✔ Stack Data Structure ✔ Parentheses Validation Logic ✔ Depth Tracking ✔ String Traversal ✔ Simulation Technique 📈 Learning Reflection Problems like this highlight how simple data structures elegantly solve structural problems. Understanding stack behavior builds strong foundations for: Expression evaluation Compiler parsing Balanced parentheses problems ✅ Day 14 Progress Update 🔥 64 Problems Solved — Still Consistent Small daily improvements → Long-term mastery 🚀 #Day14 #30DaysOfDSA #Java #LeetCode #Stack #DSAJourney #ProblemSolving #CodingConsistency #InterviewPreparation #LearningEveryday
To view or add a comment, sign in
-
-
🔍 Pattern Matching in Java: Stop Writing Boilerplate, Start Writing Intent How many times have you written this? if (obj instanceof String) { String s = (String) obj; System.out.println(s.toUpperCase()); } Java 16+ eliminated this ceremony forever. ✅ if (obj instanceof String s) { System.out.println(s.toUpperCase()); } But that's just the beginning. With Java 21, Pattern Matching exploded into something extraordinary via switch expressions: String result = switch (shape) { case Circle c -> "Area: " + Math.PI * c.radius() * c.radius(); case Rectangle r -> "Area: " + r.width() * r.height(); case Triangle t -> "Area: " + 0.5 * t.base() * t.height(); default -> "Unknown shape"; }; No casting. No NPE traps. No noise. Just pure, readable logic. 🔥 Why does this matter? → It closes the gap between Java and functional languages like Scala or Kotlin → Works beautifully with sealed classes — the compiler ensures exhaustiveness → Reduces cognitive load and bug surface area simultaneously → Makes your domain model express behavior, not just data Guarded patterns take it even further: case Integer i when i > 0 -> "Positive: " + i; case Integer i -> "Non-positive: " + i; This isn't syntactic sugar. It's a paradigm shift in how we model logic in Java. The language is finally letting us write what we mean, not what the compiler demands. Are you already using Pattern Matching in production? What's your favorite use case? Drop it below 👇 #Java #Java21 #PatternMatching #CleanCode #SoftwareEngineering #JVM #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Experimenting with Multithreading in Java – Real Performance Impact Recently, I built a multi-threaded web crawler in Java to understand the real-world impact of concurrency. The crawler scrapes product data (title + price) from a paginated website and stores it in a CSV file. 🧪 The Experiment: I ran the same crawler with different thread pool sizes. Case 1: Single Thread Execution time: ~678 seconds Tasks executed sequentially. Each HTTP request completed before the next one started. Case 2: 20 Threads (FixedThreadPool(20)) Execution time dropped dramatically. Multiple product pages were fetched in parallel, significantly reducing total runtime. 💡 Key Insight: The crawler is I/O-bound, not CPU-bound. Most of the time is spent waiting on network calls and server responses. While one thread waits for a response, other threads can continue working. That’s where multithreading creates massive performance gains. 📌 What I Learned: Thread pools drastically improve throughput for I/O-heavy systems. Too many threads can hurt performance due to context switching, memory overhead, and potential server throttling. Optimal thread count depends on CPU cores and the ratio of wait time to compute time. There’s even a formula: Optimal Threads ≈ CPU Cores × (1 + Wait Time / Compute Time) 🏗 Technical Takeaways Used ExecutorService with FixedThreadPool Implemented synchronized CSV storage for thread safety Used awaitTermination() to measure actual execution time Learned the importance of safe resource sharing in concurrent systems This experiment reinforced one key lesson: Multithreading isn’t just about parallelism — it’s about understanding where your system actually waits. #Java #Multithreading #BackendDevelopment #PerformanceEngineering #Concurrency
To view or add a comment, sign in
-
The "11th Rule" Trap: Why Java’s Map.of() Might Be Misleading You ❌ Have you ever written perfectly logical, declarative code, only to be hit by a strange Compilation Error? You look at your IDE, and it insists on an "Incompatible Types" issue, even though your classes match perfectly. I recently hit a classic, but treacherous problem, using the Map.of() method. 📋 Dispatch Map Pattern I was implementing a "Type-to-Strategy Map" to replace a messy chain of if-else and instanceof blocks. The idea is clean: a map where the key is the Rule class and the value is the mapping function. Ten rules worked flawlessly. But as soon as I added the eleventh, everything broke. 🤯 A Misleading Hint Instead of a clear "Too many arguments" message, the compiler threw a confusing: "Incompatible types: expected... " I spent 15 minutes re-verifying my code, thinking I had made a mistake in the type system. I was convinced the problem was the type of the new rule, while the actual problem was simply the quantity. The compiler's "confused" hint led me down a rabbit hole, when I should have just been counting my arguments. 💡 Why is there a limit of 10? Why can't Map.of() just use varargs like List.of() to accept any number of elements? Varargs can only handle a single type. Type Mixing: In a Map, we have Keys (K) and Values (V). Java's varargs doesn't have a syntax to say "take arguments where every first is K and every second is V". Safety: Using Object... would lose type safety and risk an odd number of arguments, leading to runtime crashes. Performance: To keep Map.of() lightning-fast and "allocation-free" (avoiding temporary arrays), JDK developers manually overloaded it 11 times (from 0 to 10 pairs). Once you hit 11, you've run out of "pre-built" templates! ✅ The Fix: Map.ofEntries() To bypass the "one-type varargs" limit, Java uses Map.ofEntries(). It wraps each pair into a Map.Entry object. Since the type is now uniform (Entry), varargs works perfectly, allowing for any number of elements. 🛠 Lessons Learned: Source over Docs: When a standard method acts weird, Command(Ctrl for Windows) + Click into the JDK source. Don’t trust the error message 100%: The compiler often "guesses" the closest mismatch, leading you away from the actual fix. The Dispatch Map Pattern: Despite this hiccup, it’s a powerful way to keep your code Open/Closed compliant and maintainable. Have you ever been misled by a cryptic compiler error? Share your stories in the comments! 👇 #java #backend #programming #cleancode #softwaredevelopment #tips #generics #jvm
To view or add a comment, sign in
-
More from this author
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