🚀 LeetCode #46 — Permutations (Backtracking in Java) Today I solved the Permutations problem using a clean swap-based backtracking approach. This problem is a great way to strengthen recursion and understand how backtracking explores all possible configurations systematically. 🧠 Problem Summary Given an array of distinct integers, generate all possible permutations. 💡 Approach Instead of using extra space to track used elements, I applied in-place swapping: Fix one index at a time Swap it with every possible candidate Recurse for the next index Backtrack (swap back) to restore the original order This ensures: ✔ All permutations are explored ✔ No duplicates ✔ Efficient space usage ✅ Java Solution class Solution { List<List<Integer>> sol = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { generate(0, nums); return sol; } public void generate(int i, int[] nums) { if (i == nums.length) { sol.add(Arrays.stream(nums).boxed().toList()); return; } for (int j = i; j < nums.length; j++) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; generate(i + 1, nums); temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } 📈 Complexity Time: O(n × n!) Space: O(n) recursion depth 🔍 Key Learnings ✨ Backtracking = Choose → Explore → Unchoose ✨ Swapping helps avoid extra memory usage ✨ Restoring state is critical for correct recursion Problems like this really improve intuition for recursion trees and algorithmic thinking. #LeetCode #Java #Backtracking #Recursion #DataStructures #Algorithms #CodingPractice #ProblemSolving #LearningJourney
Permutations Backtracking Java Solution
More Relevant Posts
-
🧠 var Keyword in Java — Type Inference Explained #️⃣ var keyword in Java Introduced in Java 10, var allows local variable type inference. 👉 The compiler automatically determines the variable type. 🔹 What is var? var lets Java infer the type from the assigned value. Instead of writing: String name = "Vijay"; You can write: var name = "Vijay"; The compiler still treats it as String. 👉 var is NOT dynamic typing 👉 Type is decided at compile-time 🔹 Why was var introduced? Before var: ⚠ Long generic types ⚠ Repeated type declarations ⚠ Verbose code ⚠ Reduced readability Example: Map<String, List<Integer>> data = new HashMap<>(); With var: var data = new HashMap<String, List<Integer>>(); Cleaner and easier to read. 🔹 Rules of using var ✔ Must initialize immediately ✔ Only for local variables ✔ Cannot use without value ✔ Cannot use for fields or method parameters ✔ Type cannot change after assignment Invalid: var x; // ❌ compile error 🔹 Where should we use var? Use var when: ✔ Type is obvious from right side ✔ Long generic types ✔ Stream operations ✔ Loop variables ✔ Temporary variables Avoid when: ❌ It reduces readability ❌ Type becomes unclear 🧩 Real-world examples var list = List.of(1, 2, 3); var stream = list.stream(); var result = stream.map(x -> x * 2).toList(); Perfect for modern functional style. 🎯 Interview Tip If interviewer asks: Is var dynamically typed? Answer: 👉 No. Java is still statically typed. 👉 var only removes repetition. 👉 Type is fixed at compile-time. 🏁 Key Takeaways ✔ Introduced in Java 10 ✔ Local variable type inference ✔ Reduces boilerplate ✔ Improves readability ✔ Not dynamic typing ✔ Use wisely #Java #Java10 #VarKeyword #ModernJava #JavaFeatures #CleanCode #ProgrammingConcepts #BackendDevelopment #JavaDeepDive #TechWithVijay #VFN #vijayfullstacknews
To view or add a comment, sign in
-
-
📌 Ever faced strange bugs in HashMap or unexpected behavior in production? The root cause often lies in how objects are compared and designed. 🗓️ Day 6/21 – Mastering Java 🚀 Topic: Immutability & Object Contracts in Java (equals(), hashCode(), toString(), == vs .equals()) As backend systems scale, correct object comparison and immutability become critical for reliability, performance, and concurrency safety. 🔹 1. Immutability in Java. An immutable object is one whose state cannot be changed after creation. Common immutable examples: - String - Wrapper classes (Integer, Long, etc.) Backend relevance: - Thread-safe by default - Safe to share across threads and requests - Ideal for caching (no accidental mutation) - Reduces synchronization overhead → better performance Immutability minimizes side effects, which is essential in multithreaded backend systems. 🔹 2. equals() & hashCode() Contract. These methods define how objects behave in collections like HashMap and HashSet. Key rule: If two objects are equal according to equals(), they must have the same hashCode(). Backend relevance: Critical for entity comparison, caching layers, and collections usage. Incorrect implementations can cause: - Missing or duplicate entries in HashMap. - Cache inconsistencies. - Hard-to-debug production issues. 🔹 3. toString() for Logging & Debugging. -> toString() converts an object into a readable string. A meaningful toString(): - Improves log clarity. - Speeds up root-cause analysis. - Makes production debugging easier. In real backend systems, logs are often your first (and sometimes only) debugger. 💡 Popular Interview Questions 1: Difference between == and .equals()? 2: Why are String objects immutable in Java? 3 : What happens if hashCode() is not overridden properly? 4 : How does immutability improve thread safety? 5: Difference between String, StringBuffer and StringBuilder? 💬 Share your answers or questions in the comments — happy to discuss! #21DaysOfJava #Strings #SCP #Immutabilty #StringBuffer #StringBuilder
To view or add a comment, sign in
-
𝐎𝐮𝐭 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐎𝐥𝐝, 𝐈𝐧 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐍𝐞𝐰 Java has evolved, and with it, a simpler, more modern approach to writing immutable data types records. In previous versions of Java, creating simple value objects required a significant amount of boilerplate code. 𝐓𝐡𝐞 𝐎𝐥𝐝 𝐖𝐚𝐲 public class Point { private final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object obj) { ... } @Override public int hashCode() { ... } @Override public String toString() { ... } } 𝐓𝐡𝐞 𝐍𝐞𝐰 𝐖𝐚𝐲 Now, with records, all that boilerplate is handled for you. A record automatically generates A constructor equals(), hashCode(), and toString() methods public record Point(int x, int y) {} When you have simple value objects with immutable data. When you don’t need additional logic like setters, mutable fields, or complex methods. #Java #JavaRecords #Programming #Coding #ImmutableData #BoilerplateCode #CleanCode #Java14 #ModernJava #SoftwareDevelopment #CodeSimplification #ObjectOrientedProgramming #JavaBestPractices #JavaTips #JavaDeveloper #TechTrends #DeveloperLife #JavaSyntax #JavaProgramming #RecordClass #TechInnovation #CodingTips #JavaCommunity
To view or add a comment, sign in
-
🛑 𝗙𝗶𝗻𝗮𝗹 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲: 𝗖𝗹𝗲𝗮𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗖𝗼𝗻𝗳𝘂𝘀𝗶𝗼𝗻 In the Java world, these three keywords sound almost identical, but they serve completely different purposes. If you're just cleaning up your code, here is the breakdown you need. 1. 𝗙𝗶𝗻𝗮𝗹 (𝗧𝗵𝗲 𝗞𝗲𝘆𝘄𝗼𝗿𝗱) Used to define 𝗶𝗺𝗺𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 or restrictions. Think of it as "the last version" of something: • 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀: Makes them constants (cannot be reassigned). • 𝗠𝗲𝘁𝗵𝗼𝗱𝘀: Prevents them from being overridden by subclasses. • 𝗖𝗹𝗮𝘀𝘀𝗲𝘀: Prevents inheritance (e.g., the String class is final). 2. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 (𝗧𝗵𝗲 𝗕𝗹𝗼𝗰𝗸) Used in 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗵𝗮𝗻𝗱𝗹𝗶𝗻𝗴 (try-catch-finally). It represents "guaranteed execution": • The code inside a finally block runs 𝗻𝗼 𝗺𝗮𝘁𝘁𝗲𝗿 𝘄𝗵𝗮𝘁—whether an exception was thrown or not. • 𝗕𝗲𝘀𝘁 𝗨𝘀𝗲: Closing file streams, database connections, or releasing resources to prevent memory leaks. 3. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲 (𝗧𝗵𝗲 𝗠𝗲𝘁𝗵𝗼𝗱) A protected method inherited from the Object class: • It is invoked by the 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 just before an object is destroyed. • 𝗦𝘁𝗮𝘁𝘂𝘀: 𝗗𝗲𝗽𝗿𝗲𝗰𝗮𝘁𝗲𝗱 since Java 9. • 𝗪𝗵𝘆? It is unpredictable, unreliable, and can cause significant performance issues. Modern Java favors try-with-resources for cleanup. #Java #Programming #Backend #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
Ever wondered how Java manages memory behind the scenes? Let’s break down some core concepts that every developer should know! 🔹 Internal Working of G1 Garbage Collector The G1 (Garbage First) collector divides the heap into equal-sized regions and prioritizes collecting the ones with the most garbage first — hence the name. It operates in phases: marking live objects, evacuating them to empty regions, and clearing the old ones. This allows predictable pause times and efficient heap utilization. 🔹 How Garbage Collector Determines Reachable Objects Starting from GC roots (like static fields, active thread stacks, and JNI references), the GC traverses object references to build a reachability graph. Any object not connected to a root is considered unreachable and eligible for collection. 🔹 Useful Annotations in Java · @Override: Indicates a method overrides a superclass method. · @Deprecated: Marks code as obsolete. · @SuppressWarnings: Suppresses compiler warnings. · @FunctionalInterface: Designates an interface for lambda expressions. 🔹 What Are Meta-Annotations? Meta-annotations are annotations applied to other annotations to define their behavior. Key examples: · @Retention: Specifies how long the annotation is retained (e.g., source, class, runtime). · @Target: Limits where the annotation can be applied (e.g., method, field). · @Documented: Includes the annotation in JavaDoc. · @Inherited: Allows annotation inheritance by subclasses. 💬 Q&A Q1: How does G1 differ from older collectors like CMS? A: Unlike CMS, G1 is region-based, performs compaction to avoid fragmentation, and offers more predictable pause times. Q2: Why is @FunctionalInterface useful? A: It ensures the interface has only one abstract method, enabling lambda usage and making the intent clear. Q3: Can we create custom annotations? A: Yes, by using meta-annotations to define retention, target, and other properties. Understanding these fundamentals can optimize performance and write cleaner, maintainable code. What other Java internals topics interest you? Share below! #Java #GarbageCollection #JVM #Annotations #SoftwareDevelopment #Coding #TechInsights
To view or add a comment, sign in
-
From APIs to Agents: With Spring AI and Java ! The landscape of AI is shifting from simple chat interfaces to dynamic, collaborative AI-Agent Systems. While Python has traditionally dominated this space, the Java community is making a massive leap forward with Spring AI and the Model Context Protocol (MCP). I’m excited to share my latest article and video tutorial where I dive deep into transitioning your Java stack to AI-Agent workflow. 📺 Watch the full tutorial & demo: https://lnkd.in/gzjKkUze 📖 Read the detailed breakdown below: https://lnkd.in/gw2e6qsk
To view or add a comment, sign in
-
🚀 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
To view or add a comment, sign in
-
Stop writing boilerplate. Let the compiler do the heavy lifting. In modern Java, you can replace a verbose data class with a single line: public record Car(String name) {} Behind the scenes, Java automatically generates: ✅ Private final fields (Immutability by default). ✅ Canonical constructor (State initialization). ✅ Accessor methods (e.g., car.name()). ✅ equals() and hashCode() (Value-based equality). ✅ toString() (Readable output). // What the JVM actually sees: public final class Car extends java.lang.Record { privatefinal String name; public Car(String name) { this.name = name; } public String name() { returnthis.name; } @Overridepublic boolean equals(Object o) { ... } @Overridepublic int hashCode() { ... } @Overridepublic String toString() { ... } } The Result? Cleaner code, fewer bugs, and zero "boilerplate fatigue." Are you still using traditional POJOs, or have you switched to Records? 👇 #Java #CleanCode #SoftwareEngineering #ProgrammingTips #ModernJava
To view or add a comment, sign in
-
📄Java clone() 1️⃣ What clone means Shallow copy → copy the Object reference Deep copy → copy the Object reference+ copy their fields deeply 2️⃣ What Java actually does by default super.clone() ➡ Copies object structure ➡ Inner objects are shared So Java clone copies: ✔ primitives ❌ references (pointer copied, not object) 3️⃣ How we make it Deep Copy Manually clone inner objects: new Location(this.location) So: super.clone() + manual cloning = Deep Copy 4️⃣ Return Type Confusion Java forces method signature: Object clone() Compiler only sees Object So we cast: User copy = (User) original.clone(); 🧠 Casting does NOT create or convert objects It only changes how compiler views the reference 5️⃣ What actually happens internally clone() → memory duplication (no constructor called) Casting → only permission to access methods Object ref = userClone; ((User)ref).getName(); // allowed after cast No new object created here. 6️⃣ Important internal fact clone() in Object is a native method Real implementation exists inside JVM (C/C++), so IDE cannot open its source code. return (User) super.clone(); → works, but only shallow copy return new User(this); → works and can be deep copy GitHub Link: https://lnkd.in/g5Zj48m6 🔖Frontlines EduTech (FLM) #java #coreJava #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #cloneMethod #deepCopy #shallowCopy
To view or add a comment, sign in
-
-
🔵 equals() vs hashCode() — Real-World Explanation In Java, equals() and hashCode() are not just methods — they are a contract that defines object identity and consistency, especially inside hash-based collections. 🧠 Conceptual View equals() answers: “Are these two objects logically the same?” hashCode() answers: “Where should this object be stored for fast access?” They work together to balance correctness and performance. 🌍 Real-World Analogy (Library System) Imagine a library: 📕 Book Content → equals() 🏷️ Shelf Number → hashCode() Two books with the same content: Must be considered the same book → equals() = true Must be placed on the same shelf → same hashCode() If identical books go to different shelves, the librarian (HashMap) will never find them efficiently. ⚙️ Internal Working (Hash-Based Collections) When you put an object into a HashMap or HashSet: hashCode() determines the bucket (location) equals() confirms the exact match inside that bucket 👉 hashCode() narrows the search 👉 equals() finalizes equality This design gives O(1) average lookup time. 📜 The Contract (Very Important) If a.equals(b) is true, then ➜ a.hashCode() == b.hashCode() must be true Same hashCode() does NOT guarantee equals() is true Breaking this contract causes: Duplicate entries Missing data during lookup Unpredictable behavior in collections 🚨 Why Interviewers Stress This It tests object design knowledge It reveals understanding of data structures It exposes real-world bug awareness It separates coders from engineers 🧩 Design Insight equals() → Business logic hashCode() → Performance optimization Both together → Correctness + Efficiency Ignoring either breaks system reliability. 💡 One-Line Takeaway equals() defines logical equality, hashCode() defines physical placement — and Java collections depend on both. #Java #CoreJava #ObjectOrientedProgramming #HashMap #HashSet #JavaInterview #BackendDevelopment #SoftwareEngineering
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
Good keep going