🚀Day 20 of #75DaysOfLeetCode LeetCode 2215 – Find the Difference of Two Arrays | Java | HashSet Approach Today I solved an interesting array + hashing problem that focuses on finding distinct elements between two arrays. 🔹 Problem Statement Given two integer arrays nums1 and nums2, return: answer[0] → all distinct integers in nums1 not present in nums2 answer[1] → all distinct integers in nums2 not present in nums1 The order of elements in the result does not matter. 📌 Example Input: nums1 = [1,2,3] nums2 = [2,4,6] Output: [[1,3], [4,6]] ✔️ 1 and 3 are in nums1 but not in nums2 ✔️ 4 and 6 are in nums2 but not in nums1 💡 Approach Instead of using nested loops (which would be inefficient), we can use HashSet: 1️⃣ Convert both arrays into sets to remove duplicates. 2️⃣ Check elements of set1 that are not in set2. 3️⃣ Check elements of set2 that are not in set1. 4️⃣ Store results in a list of lists. ⏱ Time Complexity: O(n + m) 📦 Space Complexity: O(n + m) 💻 Java Solution import java.util.*; class Solution { public List<List<Integer>> findDifference(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for(int n : nums1) set1.add(n); for(int n : nums2) set2.add(n); List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); for(int n : set1){ if(!set2.contains(n)){ list1.add(n); } } for(int n : set2){ if(!set1.contains(n)){ list2.add(n); } } List<List<Integer>> result = new ArrayList<>(); result.add(list1); result.add(list2); return result; } } 🔑 Key Takeaway: Using HashSet simplifies the problem by removing duplicates and providing O(1) lookup time. #LeetCode #Java #DSA #CodingPractice #HashSet #Arrays #ProblemSolving #SoftwareDevelopment
LeetCode 2215: Find Difference of Two Arrays with Java HashSet
More Relevant Posts
-
💬✨ STRING.INDENT() AND TRANSFORM(): SMALL JAVA APIS, BIGGER CLEAN CODE 🔸 TLDR Since Java 12, String.indent() and String.transform() make text processing much cleaner. Instead of manually splitting lines, looping, and rebuilding strings with StringBuilder, you can express the same idea in one fluent and readable pipeline. ☕✨ 🔸 WHY THIS MATTERS A lot of Java codebases still contain old-school string manipulation logic that feels heavier than the real intent. When your goal is simply: ▪️ indent some text ▪️ trim it ▪️ reformat it ▪️ chain a few transformations …you do not need ceremony anymore. Java already gives you elegant tools for that. ✅ 🔸 THE OLD WAY String[] lines = text.split("\n"); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(" ").append(line) .append("\n"); } String indented = sb.toString(); This works. But it is verbose, mechanical, and hides the real intention behind implementation details. 😅 🔸 THE MODERN WAY String indented = text.indent(4); String result = text .transform(String::strip) .transform(s -> s.replace(" ", "-")); Now the code says exactly what it does: ▪️ indent the text ▪️ strip extra outer spaces ▪️ replace spaces with dashes That is much easier to read at a glance. 👀 🔸 WHY THE MODERN WAY WINS ▪️ BUILT-IN Indentation is a common need, and indent() turns it into a direct API call. ▪️ CHAINABLE transform() lets you build a fluent pipeline instead of scattering temporary variables everywhere. ▪️ CLEANER INTENT The reader sees the purpose immediately, not the plumbing. ▪️ LESS BOILERPLATE No manual line splitting. No explicit loop. No StringBuilder dance. ▪️ BETTER TEACHING VALUE This is the kind of API that helps newer developers write code that looks modern and expressive from day one. 🔸 HOW IT WORKS ▪️ indent(n) adds indentation to each line of the string ▪️ transform(fn) applies a function to the string and returns the result ▪️ together, they help create readable string-processing pipelines 🔸 WHEN TO USE IT Use these APIs when: ▪️ formatting multiline text ▪️ preparing console output ▪️ adjusting generated content ▪️ applying several string operations in sequence ▪️ improving readability of utility code 🔸 TAKEAWAYS ▪️ String.indent() and String.transform() are available since Java 12 ▪️ they reduce boilerplate for common text operations ▪️ transform() is especially useful for fluent string pipelines ▪️ the biggest win is readability, not just fewer lines of code ▪️ small modern APIs can make everyday Java feel much cleaner #Java #Java12 #JDK #StringAPI #CleanCode #JavaDeveloper #SoftwareEngineering #Programming #BackendDevelopment #CodeQuality #DeveloperTips #ModernJava Go further with Java certification: Java👇 https://bit.ly/javaOCP Spring👇 https://bit.ly/2v7222 SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
-
Java 26 just dropped! But most developers have not even adopted Java 21 features yet. Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) { case ACTIVE: label = "Active"; break; case PENDING: label = "Pending"; break; default: label = "Unknown"; } // After: String label = switch (status) { case ACTIVE -> "Active"; case PENDING -> "Pending"; default -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """ { "name": "Alice", "role": "admin" } """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) { case Integer i -> "int: " + i; case String s -> "str: " + s; default -> "unknown"; }; // Even better with guards: return switch (order) { case Order o when o.isPaid() -> "Paid"; case Order o when o.isPending() -> "Pending"; default -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip(); // Unicode-aware trim() input.isBlank(); // true if empty or whitespace input.repeat(3); // repeats string N times "line1\nline2".lines(); // Stream by line "hello %s".formatted("world"); // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚨 This Java code looks 100% illegal. But it compiles. It runs. And it does something MAGICAL. outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // ← THIS LOOKS WRONG! } System.out.println(i + "," + j); } } Output: 0,0 0,1 0,2 1,0 Then it STOPS. Completely. Both loops. Gone. 💨 First time I saw this I thought: ❌ Is "outer" a variable? ❌ Is this some framework keyword? ❌ Did someone hack Java?! Nope. This is 100% pure Java. And it's called ➡️ Labeled break ━━━━━━━━━━━━━━━━━━ 🔍 What is happening here? ━━━━━━━━━━━━━━━━━━ Normally break only exits the INNER loop. But what if you want to break out of the OUTER loop from deep inside nested loops? Java gives you a secret weapon: You can NAME a loop with a label! outer: ← this names the outer loop Then break outer instantly kills BOTH loops no matter how deep you are! 🎯 Same trick works with continue: outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) { continue outer; // skips to next i! } System.out.println(i + "," + j); } } Output: 0,0 1,0 2,0 continue outer skips the rest of the INNER loop and jumps straight to the next iteration of OUTER! 🤯 ━━━━━━━━━━━━━━━━━━ 💡 When to use this? ━━━━━━━━━━━━━━━━━━ ✅ Searching in a 2D matrix — stop when found ✅ Parsing nested data — skip entire blocks ✅ Game loops — exit multiple layers cleanly ✅ Any time nested breaks make your code messy I am a Java beginner and this blew my mind today. Imagine dropping this in a Java interview! 🏆 Most senior developers I showed this to said: "Wait... Java can do THAT?!" Comment "LABEL" if you already knew this! Comment "MIND BLOWN" if you didn't! 👇 Follow me — I find Java secrets that nobody talks about. 🚀 #Java #JavaDeveloper #JavaTips #HiddenJava #JavaMagic #CodingSecrets #JavaInterview #LearnJava #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
To view or add a comment, sign in
-
✨ Most Useful Keywords In Java✨ ➡️final : The final keyword can be applied to classes, variables, methods, and blocks. Once assigned, it cannot be changed. A final class cannot be extended, a final variable cannot be reassigned, and a final method cannot be overridden. ➡️static : The static keyword can be applied to variables, methods, and blocks. Static members can be accessed using the class name without creating an object. Static methods cannot be overridden. ➡️abstract : Used to create a class or method that is incomplete and must be implemented by sub-classes ➡️assert : Used for debugging to test assumptions during runtime ➡️boolean : Represents a logical data type with values true or false ➡️break : Terminates a loop or switch statement immediately ➡️byte : Data type to store 8-bit integer values ➡️case : Defines a branch in a switch statement ➡️catch : Handles exceptions raised in a try block ➡️char : Stores a single character ➡️class : Used to declare a class ➡️continue : Skips the current loop iteration and continues with the next one ➡️default : Executes when no case matches in switch Defines default methods in interfaces ➡️do : Used in a do-while loop (executes at least once) ➡️double : Stores 64-bit decimal numbers ➡️else : Executes when an if condition is false ➡️enum :Defines a fixed set of constants ➡️extends : Used by a subclass to inherit another class ➡️finally : Block that always executes, used for cleanup ➡️float : Stores 32-bit decimal values ➡️for : Used for loop execution with initialization, condition, and increment ➡️if : Executes code when a condition is true ➡️implements : Used by a class to implement an interface ➡️import : Allows access to classes defined in other packages ➡️instanceof : Checks whether an object belongs to a specific class ➡️int : Stores 32-bit integer values ➡️interface : Used to declare a contract that classes must follow ➡️long : Stores 64-bit integer values ➡️new : Creates an object or instance ➡️package : Groups related classes and interfaces ➡️return : Sends a value back from a method and exits it ➡️short : Stores 16-bit integer values ➡️static : Belongs to the class, not object ➡️super : Refers to parent class object or constructor ➡️switch : Selects execution paths based on an expression ➡️synchronized : Controls thread access to prevent data inconsistency ➡️this : Refers to the current object ➡️throw : Explicitly throws an exception ➡️throws : Declares exceptions that a method may pass upward ➡️transient : Prevents variable from being serialized ➡️try : Wraps code that may generate exceptions ➡️void : Indicates a method returns no value ➡️volatile : Ensures variable value is read from main memory, not cache ➡️while: Executes a loop while condition remains true ➡️var: var enables local variable type inference ➡️record: record is a special immutable class used to store data only #javafeatures #oops #opentowork #fresher #softwareengineer #hiring #javadeveloper
To view or add a comment, sign in
-
Day 15 Java Practice: Find Product with Maximum Total Quantity While practicing Java, I worked on a small problem involving strings, arrays, and maps. 👉 Given product data with quantity like: {"xyz 19","abc 30","xyz 21","abc 23"} The goal was to: Sum the quantities for the same product Find which product has the maximum total quantity 🧠 Approach: Split each string to get product name and quantity Store and add quantities using a HashMap Traverse the map to find the maximum value ============================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { String a []={"xyz 19","abc 30","xyz 21","abc 23"}; Map<String,Integer>hmap=new HashMap<String,Integer>(); for(String s : a) { String data []=s.split(" "); String name=data[0]; int value=Integer.parseInt(data[1]); hmap.put(name,hmap.getOrDefault(name,0)+value); } int max=0; String result=""; for(Map.Entry<String,Integer>entry:hmap.entrySet()) { if(entry.getValue()>max) { max=entry.getValue(); result=entry.getKey(); } } System.out.println(result+" "+max); } } Output: abc 53 #JavaDeveloper #AutomationEngineer #CodingPractice #Collections #ProblemSolving #Learning
To view or add a comment, sign in
-
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
🚀 Today I dived deep into Exception Handling in Java! Have you ever seen a "software not responding" popup or had an app suddenly crash?,. That is often because of an unhandled exception. What is an Exception? In Java, an exception is an unusual event that occurs during the runtime (execution) of a program,,. It is usually triggered by faulty user input—like trying to divide a number by zero or providing a string when a number is expected,,. If these aren't handled, they lead to abrupt termination, which ruins the user experience and can cause significant losses for a company,. How it works behind the scenes: When a problem occurs, the JVM automatically creates an Exception Object,. This object contains the "What" (type of error), "Where" (line number), and "Why" (the reason),. If we don't catch it, the Default Exception Handler prints the error and stops the program immediately,. The Solution: Try-Catch Blocks To ensure normal termination, we follow three simple steps: 1.Identify risky lines of code where a problem might occur,. 2.Place that code inside a try block,. 3.Write a catch block to intercept the exception object and handle it gracefully,. Pro Tip: The Order of Catch Blocks Matters! ⚠️ You can have multiple catch blocks for different errors (like ArithmeticException or ArrayIndexOutOfBoundsException),. However, you must always put specific exceptions first and the general Exception class last,. If you put the general one first, the specific ones become unreachable code because the general class has the capability to catch everything. Code Example: import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Connection established."); try { // Step 1 & 2: Identify and wrap risky code, System.out.print("Enter numerator: "); int a = scan.nextInt(); System.out.print("Enter denominator: "); int b = scan.nextInt(); int result = a / b; // Risky line: ArithmeticException if b=0 System.out.println("Result: " + result); } catch (ArithmeticException e) { // Step 3: Handle specific exception, System.out.println("Error: Please enter a non-zero denominator."); } catch (Exception e) { // General catch-all for other unexpected issues System.out.println("Some technical problem occurred."); } System.out.println("Connection terminated.");, } } Looking forward to exploring rethrowing and ducking exceptions tomorrow!. #Java #Coding #BackendDevelopment #ExceptionHandling #LearningJourney #SoftwareEngineering #TapAcademy
To view or add a comment, sign in
-
-
🚀 Understanding Generics in Java – Write Flexible & Type-Safe Code If you’ve ever worked with collections like List or Map, you’ve already used Generics — one of the most powerful features in Java. 🔹 What are Generics? Generics allow you to write classes, interfaces, and methods with a placeholder for the data type. This means you can reuse the same code for different data types while maintaining type safety. 🔹 Why use Generics? ✔️ Eliminates type casting ✔️ Provides compile-time type safety ✔️ Improves code reusability ✔️ Makes code cleaner and more readable 🔹 Simple Example: List<String> names = new ArrayList<>(); names.add("Sneha"); // names.add(10); ❌ Compile-time error 🔹 Generic Class Example: class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹 🔥 Advanced Concepts Explained 🔸 1. Bounded Types (Restricting Types) You can limit what type can be passed: class NumberBox<T extends Number> { T value; } 👉 Only Integer, Double, etc. are allowed (not String) 🔸 2. Wildcards (?) – Flexibility in Collections ✔️ Unbounded Wildcard List<?> list; 👉 Can hold any type, but limited operations ✔️ Upper Bounded (? extends) List<? extends Number> list; 👉 Accepts Number and its subclasses 👉 Used when reading data ✔️ Lower Bounded (? super) List<? super Integer> list; 👉 Accepts Integer and its parent types 👉 Used when writing data 💡 Rule: PECS → Producer Extends, Consumer Super 🔸 3. Generic Methods public <T> void print(T data) { System.out.println(data); } 👉 Works independently of class-level generics 🔸 4. Type Erasure (Important for Interviews) Java removes generic type info at runtime: List<String> → List 👉 No runtime type checking 👉 Only compile-time safety 🔸 5. Multiple Bounds <T extends Number & Comparable<T>> 👉 A type must satisfy multiple conditions 🔸 6. Restrictions of Generics ❌ Cannot use primitives (int, double) → use wrappers ❌ Cannot create generic arrays ❌ Cannot use instanceof with generics 💡 Final Insight: Generics are not just a feature—they are a design tool that helps build scalable, reusable, and maintainable applications. Mastering advanced concepts like wildcards and type erasure can set you apart as a strong Java developer. #Java #Generics #AdvancedJava #Programming #JavaDeveloper #Coding #TechInterview
To view or add a comment, sign in
-
🚀 Day 4/100 — If-Else & Switch in Java 🚦 Conditions are the brain of a program. They help your program make decisions based on different situations. In Java, the most common decision-making statements are if, else if, else, and switch. 🔹 If-Else Statement Used when a program needs to execute code based on a condition. Example: int age = 20; if(age >= 18){ System.out.println("Eligible to vote"); }else{ System.out.println("Not eligible to vote"); } ✔ If the condition is true, the first block runs. ✔ If it's false, the else block runs. 🔹 Else If Ladder Used when there are multiple conditions. ⚠️ Important: Java checks conditions top to bottom, and once one condition becomes true, the rest are skipped. Example: int marks = 85; if(marks >= 90){ System.out.println("Grade A"); } else if(marks >= 75){ System.out.println("Grade B"); } else if(marks >= 60){ System.out.println("Grade C"); } else{ System.out.println("Grade D"); } 🔹 Switch Statement Used when comparing one variable with multiple values. Example: int day = 3; switch(day){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } ⚠️ Important: If you forget break, Java will execute all cases after that one (called fall-through). Example without break: int num = 1; switch(num){ case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); } Output: One Two Three 🔴 Mini Example — Pass or Fail int marks = 40; if(marks >= 35){ System.out.println("Pass"); }else{ System.out.println("Fail"); } 🎯 Challenge: Build a Grade Calculator using if-else. Example logic: 90+ → Grade A 75–89 → Grade B 60–74 → Grade C Below 60 → Grade D Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaLearning #ProgrammingJourney
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