🚀 Day 42 of 50 – Java LeetCode Challenge Today’s challenge was "21. Merge Two Sorted Lists" — a classic linked list problem that enhances your understanding of pointer manipulation and list traversal. The task focuses on merging two sorted linked lists into one sorted list efficiently. ⏱ Today’s Task – Merge Two Sorted Lists 📝 Problem Statement: You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The new list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. 🔧 Constraints: 1️⃣ The number of nodes in both lists is in the range [0, 50] 2️⃣ -100 ≤ Node.val ≤ 100 3️⃣ Both list1 and list2 are sorted in non-decreasing order 🧪 Examples: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] ✅ Input: list1 = [], list2 = [] Output: [] ✅ Input: list1 = [], list2 = [0] Output: [0] ✅ 💻 My Java Solution: class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { // Create a dummy node to act as the head of the new merged list ListNode dummy = new ListNode(-1); ListNode current = dummy; // Traverse both lists while both have nodes while (list1 != null && list2 != null) { if (list1.val <= list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; // move forward } // If one list is exhausted, connect the remaining nodes of the other list if (list1 != null) { current.next = list1; } else { current.next = list2; } // Return the merged list starting after the dummy node return dummy.next; } } 🔍 Takeaways: ✅ Efficiently handles merging using a dummy node ✅ Ensures a single pass O(n + m) time complexity ✅ Demonstrates pointer manipulation and linked list traversal 💡 Core Concepts: Linked List traversal Pointer management Dummy head node usage Iterative merging 🎯 Day 42 completed — 8 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #LinkedList #Day42 #JavaProgramming #CodeNewbie #LearnInPublic
"Java LeetCode Challenge: Merging Sorted Linked Lists"
More Relevant Posts
-
🚀 Day 23 – Java Switch Case with Grouped Cases + Seasons Logic Today in my Java learning journey, I explored how switch-case can handle multiple case values together and how we can use it to build real-life logic like detecting months and seasons. 🔥 Main Concept (Simple Explanation) You can group multiple case values in a switch. When the value matches any grouped case, the same block runs. Inside that block, you can use if-else for finer decision-making. This helps avoid writing too many switch cases. 💻 Java Code Example ------------------------------------code start----------------------------------- public class SwitchSeasonEx1 { public static void main(String[] args) { byte B = 5; switch (B) { case 1 + 2: case 1 + 3: case 1 + 4: case 1 + 5: if (B == 3) { System.out.println("This is the March month"); } else if (B == 4) { System.out.println("This is the April month"); } else if (B == 5) { System.out.println("This is the May month"); } else System.out.println("This is the June month"); System.out.println("And it is the Summer season"); break; case 1 + 6: case 1 + 7: case 1 + 8: case 1 + 9: if (B == 7) { System.out.println("This is the July month"); } else if (B == 8) { System.out.println("This is the August month"); } else if (B == 9) { System.out.println("This is the September month"); } else System.out.println("This is the October month"); System.out.println("This is the Rainy season"); break; case 2 + 9: case 3 + 9: case 1: case 2: if (B == 10 + 1) { System.out.println("This is the November month"); } else if (B == 10 + 2) { System.out.println("This is the December month"); } else if (B == 1) { System.out.println("This is the January month"); } else System.out.println("This is the February month"); System.out.println("This is the Winter season"); break; } } } ----------------------------------code output----------------------------------- This is the May month And it is the Summer season ------------------------------------code end----------------------------------- 💡 What I Learned Today Switch cases can use expressions like (1 + 2). Multiple cases can point to the same code block. Good for writing cleaner and structured logic. 🔖 #JavaLearning #Day23 #SwitchCase #CodingJourney #100DaysOfCode #BackendDevelopment #JavaBeginners #SoftwareEngineering #ProgrammingLife #DevOps #Jenkins #Docker #CloudComputing #LearningEveryday
To view or add a comment, sign in
-
-
"🚀 Day 44 of 50 – Java LeetCode Challenge" Today’s challenge was “228. Summary Ranges” — a neat array-based problem that enhances your understanding of iteration, range detection, and string manipulation in Java. The goal is to summarize continuous sequences of numbers into compact range strings. ⏱ Today’s Task – Summary Ranges 📝 Problem Statement: You are given a sorted unique integer array nums. A range [a, b] is defined as all integers from a to b (inclusive). Return the smallest sorted list of ranges that covers all numbers in the array exactly. Each range should be represented as: "a->b" if a != b "a" if a == b 🧪 Examples: Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] ✅ Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] ✅ 🔧 Constraints: 0 <= nums.length <= 20 -2³¹ <= nums[i] <= 2³¹ - 1 All values are unique and sorted in ascending order 💻 My Java Solution: import java.util.*; class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int start = nums[0]; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1] + 1) { if (start == nums[i - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[i - 1]); } start = nums[i]; } } if (start == nums[nums.length - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[nums.length - 1]); } return result; } } 🔍 Takeaways: ✅ Efficient handling of continuous integer sequences ✅ Smart use of loop tracking and condition checks ✅ Clean, readable implementation with O(n) time complexity ✅ Handles edge cases gracefully (like empty arrays or single elements) 💡 Core Concepts: 📘 Array traversal and pattern detection 📘 String concatenation and list building 📘 Conditional logic for sequence grouping 🎯 Day 44 completed — 6 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #DataStructures #JavaProgramming #Day44 #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
🔹 Understanding Java Tokens 🔹 In Java, tokens are the basic building blocks of a program. The compiler uses these to understand and execute your code. There are five main types of tokens: 1️⃣ Identifiers 🏷️ Definition: Identifiers are names given to elements like variables, methods, classes, objects, interfaces, and packages in Java. 🔸Composition: Identifiers can be a combination of: Uppercase letters {A-Z} Lowercase letters {a-z} Digits {0-9} Underscore _ 🔸Rules: 1.Must start with a letter, $, or _ (cannot start with a number) 2.Cannot use Java keywords 3.Must follow Java naming conventions: Examples: int _age; int $age; int age123; int _5; int _$; Naming Conventions: 1.Class/Interface: Class name should be noun. Class name must starts with uppercase letter and all internal words must be capitalized. Example: Student, StudentDetails 2.Variable: Variable name should start with lower case and all internal words must be capitalized. Example: details, marks, studentDetails 3.Method: Method name should start with lower case and all internal words must be capitalized. Example: void get(), void getDetails() 4.Object: Object name should start with lower case and all internal words must be capitalized. Example: bankAccount 5.Packages: Package name must start with lowercase and main package and its subpackage seperated by dot operator(.) Example: com, com.oop, com.cg.oop 2️⃣ Keywords 🔑 Definition: Keyword is a reserved word. Every keyword has specific meaning and functionality. Must not be used as identifier. 🔸Examples: int, class, public, if etc.. 🔸Purpose: Helps the compiler understand the structure and logic of the program. 3️⃣ Operators ➕➖✖️➗ Definition: Symbols used to perform operations on variables and values. 🔸Types: 1.Arithmetic: +, -, *, /, % 2.Relational: ==, !=, >, < 3.Logical: &&, ||, ! 4.Assignment: =, +=, -= 🔸Example: int sum = a + b; boolean result = (x > y) && (x != z); 4️⃣ Literals 💎 Definition: Literals are the fixed values which we can assigned to the variables. Types: 1.Integer Literals: These are numbers without decimal point. 2.Floating Point Literals: These are numbers with decimal point. 3.Character Literals: These can be single digit, single alphabet, any special character.(Only single space is allowed). And it must be enclosed within in single quotes(' ') 4.String Literals: Strings must be enclosed within double quotes(" ") 5.Boolean Literals: Allows only true or false 5️⃣ Separators 🛑 Definition: Seperators used to separate different parts of our program. 🔸Examples: 1. ; → ends a statement 2. { } → defines a block of code 3. ( ) → used in method calls or conditions 4. [ ] → used for arrays 5. → separates multiple items 🔸Examples: for(int i=0; i<5; i++) { System.out.println(i); } Thanks to my mentor Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam
To view or add a comment, sign in
-
-
"🚀Day 43 of 50 – Java LeetCode Challenge" Today’s challenge was "20. Valid Parentheses" — a fundamental stack-based problem that strengthens your understanding of bracket matching and data structure usage. The goal is to determine whether a given string of parentheses is valid based on correct opening and closing order. ⏱ Today’s Task – Valid Parentheses 📝 Problem Statement: Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. ✅ A string is valid if: 1️⃣ Every open bracket has a corresponding closing bracket of the same type. 2️⃣ Brackets are closed in the correct order. 3️⃣ Every close bracket must have an open bracket before it. 🧪 Examples: Input: s = "()" Output: true ✅ Input: s = "()[]{}" Output: true ✅ Input: s = "(]" Output: false ❌ Input: s = "([])" Output: true ✅ Input: s = "([)]" Output: false ❌ 🔧 Constraints: 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}' 💻 My Java Solution: import java.util.*; class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put('}', '{'); map.put(']', '['); for (char c : s.toCharArray()) { if (map.containsKey(c)) { char top = stack.isEmpty() ? '#' : stack.pop(); if (top != map.get(c)) return false; } else { stack.push(c); } } return stack.isEmpty(); } } 🔍 Takeaways: ✅ Efficient use of a stack for bracket matching ✅ Clean implementation using a HashMap for bracket pairs ✅ Time complexity O(n) — single traversal through the string ✅ Space complexity O(n) — in worst case (all open brackets) 💡 Core Concepts: Stack data structure HashMap for mapping bracket pairs Iterative traversal and validation Balanced parenthesis logic 🎯 Day 43 completed — 7 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Stack #DataStructures #Day43 #JavaProgramming #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
#DAY55 #100DaysOFCode | Java Full Stack Development #Day55 of my #100DaysOfCode – Java Topic-> Lambda Expression in Java A Lambda Expression in Java is a short way to write anonymous functions (functions without a name). It was introduced in Java 8 to make code more concise, readable, and functional—especially when working with functional interfaces. Syntax: (parameter_list) -> { body } Parts: Parameter list – the inputs to the lambda (like method parameters) Arrow token (→) – separates parameters and body Body – contains the code to execute (can be one line or multiple) Example: Without Lambda: interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = new Greeting() { public void sayHello() { System.out.println("Hello, World!"); } }; g.sayHello(); } } With Lambda: interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = () -> System.out.println("Hello, World!"); g.sayHello(); } } Simpler and cleaner! When to Use Lambdas: Lambdas are used when you have a functional interface, i.e., an interface with only one abstract method. Examples: Runnable (from threads) Comparator<T> ActionListener Custom interfaces with one abstract method Example with Parameters: interface Add { int sum(int a, int b); } public class Main { public static void main(String[] args) { Add add = (a, b) -> a + b; System.out.println("Sum: " + add.sum(5, 3)); } } 🏗️ Lambda Expression Types: No parameters: () -> System.out.println("Hello!"); Single parameter: (x) -> System.out.println(x); Multiple parameters: (a, b) -> a + b; With multiple statements (use braces {}): (a, b) -> { int result = a + b; return result; }; Advantages: Reduces boilerplate code Improves readability Encourages functional-style programming Easy to use with Java Stream API and Collections Example with Collections: import java.util.*; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Rakesh", "Sai", "Kiran"); // Using lambda with forEach names.forEach(name -> System.out.println("Hello, " + name)); } } A big thanks to my mentor Gurugubelli Vijaya Kumar Sir and the 10000 Coders for constantly guiding me and helping me build a strong foundation in programming concepts. #Java #Coding #Programming #100DaysOfCode #JavaProgramming #CodeNewbie #LearnToCode #Developer #Tech #ProgrammingTips #JavaDeveloper #CodeDaily #DataStructures #CodingLife
To view or add a comment, sign in
-
-
#DAY47 #100DaysOFCode | Java Full Stack Development #Day47 of my #100DaysOfCode – Java Topic-> Lambda Expression in Java A Lambda Expression in Java is a short way to write anonymous functions (functions without a name). It was introduced in Java 8 to make code more concise, readable, and functional—especially when working with functional interfaces. Syntax: (parameter_list) -> { body } Parts: Parameter list – the inputs to the lambda (like method parameters) Arrow token (→) – separates parameters and body Body – contains the code to execute (can be one line or multiple) Example: Without Lambda: interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = new Greeting() { public void sayHello() { System.out.println("Hello, World!"); } }; g.sayHello(); } } With Lambda: interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = () -> System.out.println("Hello, World!"); g.sayHello(); } } Simpler and cleaner! When to Use Lambdas: Lambdas are used when you have a functional interface, i.e., an interface with only one abstract method. Examples: Runnable (from threads) Comparator<T> ActionListener Custom interfaces with one abstract method Example with Parameters: interface Add { int sum(int a, int b); } public class Main { public static void main(String[] args) { Add add = (a, b) -> a + b; System.out.println("Sum: " + add.sum(5, 3)); } } 🏗️ Lambda Expression Types: No parameters: () -> System.out.println("Hello!"); Single parameter: (x) -> System.out.println(x); Multiple parameters: (a, b) -> a + b; With multiple statements (use braces {}): (a, b) -> { int result = a + b; return result; }; Advantages: Reduces boilerplate code Improves readability Encourages functional-style programming Easy to use with Java Stream API and Collections Example with Collections: import java.util.*; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Rakesh", "Sai", "Kiran"); // Using lambda with forEach names.forEach(name -> System.out.println("Hello, " + name)); } } A big thanks to my mentor Gurugubelli Vijaya Kumar Sir and the 10000 Coders for constantly guiding me and helping me build a strong foundation in programming concepts. #Java #Coding #Programming #100DaysOfCode #JavaProgramming #CodeNewbie #LearnToCode #Developer #Tech #ProgrammingTips #JavaDeveloper #CodeDaily #DataStructures #CodingLife
To view or add a comment, sign in
-
-
Java secrets jo literally 0.000001% ko bhi nahi pate! 🔥 --- Post 1: Java mein "Unicode escape sequence" se code execute!🤯 ```java public class BlackMagic { public static void main(String[] args) { \u0069\u0066\u0028\u0074\u0072\u0075\u0065\u0029\u007b \u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0022\u0042\u006c\u0061\u0063\u006b\u0020\u004d\u0061\u0067\u0069\u0063\u0022\u0029\u003b \u007d } } ``` Output: Black Magic Kyun? Pure code ko Unicode mein convert kiya gaya hai! Java compiler pehle Unicode decode karta hai,phir compile! 💀 --- Post 2: Java mein "annotation processor" ka black magic!🔥 ```java @Deprecated public class GhostClass { // Ye class compile time pe modify ho sakti hai! } // Annotation processor ise aise modify kar sakta hai: public class GhostClass { @Deprecated public void newMethod() { System.out.println("Injected at compile time!"); } } ``` Secret: Annotation processors compile time pe code modify/Generate kar sakte hain!💡 --- Post 3: Java mein "reflection" se private method call!🚀 ```java import java.lang.reflect.Method; public class Hack { private void secret() { System.out.println("Private method called!"); } public static void main(String[] args) throws Exception { Hack obj = new Hack(); Method method = Hack.class.getDeclaredMethod("secret"); method.setAccessible(true); // ✅ Accessibility on method.invoke(obj); // Private method call! } } ``` Output: Private method called! Kya scene hai? Reflection se koi bhi private method call kar sakte ho!💪 --- Post 4: Java bytecode manipulation ka secret!🔮 ```java // Normal class public class Victim { public void show() { System.out.println("Original"); } } // Bytecode modify karne ke baad: public class Victim { public void show() { System.out.println("Hacked by Bytecode!"); } } ``` Tools: ASM,Javassist, ByteBuddy se runtime pe class modify kar sakte ho! 💀 --- yeh secrets sirf Java ke creators ko pata honge! 😎
To view or add a comment, sign in
-
🚀 Top Java 11 Features You Should Know Java 11 (LTS) brings several powerful updates for developers. Here’s a quick breakdown of the highlights: 1️⃣ Run Java Files Without Compilation 💻 Previously, we had to compile Java programs with javac and then run the .class files. Now, for single-file programs, you can run directly: java MyProgram.java Java compiles temporarily in memory, executes it, and no .class file is created. ⚠️ This means only the source code is needed for sharing, not compiled bytecode. 2️⃣ New String Methods 🧩 Java 11 adds several handy utilities to the String class: " ".isBlank(); // true "Hello\nWorld".lines().forEach(System.out::println); " Java ".strip(); // "Java" (Unicode-aware) "Hi ".repeat(3); // "Hi Hi Hi " 3️⃣ Files Utility Enhancements 📂 Simpler file I/O with Files.readString() and Files.writeString(): Path path = Files.writeString(Files.createTempFile("demo", ".txt"), "Java 11"); String content = Files.readString(path); System.out.println(content); // "Java 11" 4️⃣ var in Lambda Parameters ⚡ var can now be used in lambda expressions, allowing annotations and improving readability: List<String> list = List.of("A", "B", "C"); list.stream() .map((var s) -> s.toLowerCase()) .forEach(System.out::println); Note: * var can also be used for local variables. * It is not a datatype, but a type inference reference — the compiler determines the actual type at compile time. * For local variables, var must be initialized at the time of declaration so the compiler can infer the type. * This feature for local variables was introduced in Java 10. 5️⃣ HTTP Client Standardization 🌐 The experimental HTTP client is now fully standardized in java.net.http: var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.github.com")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); Supports HTTP/1.1, HTTP/2, and WebSockets. 6️⃣ Garbage Collector Improvements 🧹 Epsilon GC: No-op GC for performance testing. ZGC: Low-latency garbage collector (experimental). 7️⃣ Deprecations & Removals 🧾 Java EE & CORBA modules removed (javax.xml.bind, java.activation) JavaFX removed from JDK (available separately) 8️⃣ Java Flight Recorder (JFR) ☁️ Integrated into OpenJDK for profiling and production monitoring. 9️⃣ Nest-Based Access Control 🏗️ Simplifies private access between nested classes, removing synthetic bridge methods. 🔟 TLS 1.3 Support ⚙️ Enhanced security and performance in JSSE with TLS 1.3. 🔥 Java enthusiasts, unite! 🔥 Love exploring juicy Java tips, tricks, and features? Follow me for insights that make coding fun and practical! 💻☕ Let’s level up your Java game! 🚀 #Java11 #JavaLTS #Programming #SoftwareDevelopment #CleanCode #JavaDevelopers #FullStackDevelopment #TechTrends #CodingTips #JavaFeatures #JavaFullStackDevelopment #BackendDevelopment #CodeWithMohan
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