"🚀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
"Day 43: Solving '20. Valid Parentheses' with Java"
More Relevant Posts
-
"🚀 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
-
-
Here are some fun basic Java code snippets to refresh the fundamental understanding. Guess the output! How many did you get right? 1.➡️ public class OverloadExample { public void show(Object obj) { System.out.println("Cat"); } public void show(String str) { System.out.println("Dog"); } public static void main(String[] args) { OverloadExample example = new OverloadExample(); example.show(null); } } 2.➡️ public class ConstructorTest { void ConstructorTest() { System.out.println("Hello"); } public static void main(String[] args) { ConstructorTest ct = new ConstructorTest(); } } 3.➡️ public class IncrementTest { public static void main(String[] args) { int x = 5; System.out.println(x++ + ++x); } } 4.➡️ public class LoopTest { public static void main(String[] args) { int i = 0; for(; i < 3; i++); System.out.println(i); } } 5.➡️ public class BooleanTest { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; System.out.println(b1 & b2); System.out.println(b1 && b2); } } 6.➡️ class Main { public static void main(String[] args) { boolean b = false; System.out.println(b & test()); System.out.println("============================"); System.out.println(b && test()); } public static boolean test() { System.out.println("Called"); return false; } } 7.➡️ public class CastTest { public static void main(String[] args) { double d = 9.78; int i = (int) d; System.out.println(i); } } 8.➡️ public class PrePostTest { public static void main(String[] args) { int x = 2; int y = x++ * 3 + ++x; System.out.println(y); } } 9.➡️ public class CharTest { public static void main(String[] args) { char c = 'A'; c += 1; System.out.println(c); } } 10. ➡️public class LogicalTest { public static void main(String[] args) { int a = 5, b = 10; System.out.println(a < b || b++ < 15); System.out.println(b); } }
To view or add a comment, sign in
-
🚀 The 3 Java Maps That Outperformed HashMap (and Made My Code 3× Faster) Most Java developers swear by HashMap. It’s our go-to. Reliable. Familiar. Always the first choice. But here’s the thing 👉 HashMap isn’t always the best tool for the job. A few months ago, I was chasing down latency issues in a high-traffic service. After hours of profiling, the culprit wasn’t a slow DB, not network lag… It was a plain old HashMap. Turns out, using the wrong map in the wrong place can quietly crush performance. So I replaced it — and my code ran 3× faster. Here are the 3 hidden gems that changed everything 👇 1️⃣ WeakHashMap — The Self-Cleaning Cache 🧹 Most developers use HashMap for caching. But HashMap never forgets — objects stay until you manually remove them. That’s how memory leaks start. WeakHashMap fixes that by holding weak references to keys. Once a key is no longer referenced elsewhere, the GC wipes it automatically. Map<UserSession, String> cache = new WeakHashMap<>(); cache.put(new UserSession("u123"), "Active"); ✅ Perfect for temporary caches or listeners. ❌ Not for data that must persist. My service’s memory stabilized instantly after switching to it. 2️⃣ IdentityHashMap — When .equals() Betrays You 🧠 Ever had two different objects that look “equal”? HashMap treats them as the same key — because it uses .equals() and .hashCode(). IdentityHashMap doesn’t. It uses reference equality (==). Map<Object, String> map = new IdentityHashMap<>(); map.put(new String("Hello"), "A"); map.put(new String("Hello"), "B"); System.out.println(map.size()); // 2 This saved me from hours of debugging “why is my key missing?” nightmares. ✅ Great for frameworks, DI containers, parsers. ❌ Avoid if logical equality is intended. 3️⃣ EnumMap — The Ferrari of Fixed Keys 🏎️ If your keys are enums, stop using HashMap. Seriously. EnumMap is backed by an array, not hashes.That means O(1) lookups and zero overhead. enum Status { NEW, PROCESSING, DONE } Map<Status, String> map = new EnumMap<>(Status.class); map.put(Status.NEW, "Queued"); In my benchmarks, it was 2–3× faster than HashMap for enum keys. ✅ Type-safe, compact, and blazing fast. ❌ Only for enum-based keys. ⚡ Quick Decision Guide Goal Use This Map -------------------- ----------------- Auto-cleanup WeakHashMap Compare by reference IdentityHashMap Enum keys EnumMap General purpose HashMap 🧩 The Bigger Lesson We obsess over frameworks, cloud, and architecture — but sometimes raw data structures make the biggest difference. The right Map can reduce GC pressure, CPU load, and subtle equality bugs. The wrong one can silently waste thousands of cycles per second. So next time, pause before typing new HashMap<>(). There might be a better tool for that job. #Java #Performance #CleanCode #SystemDesign #HashMap #Collections #BackendDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
🚀 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
To view or add a comment, sign in
-
-
Java ke parallel universe ke secrets! 🔥 --- Post 1: Java ka "Hidden Class" API - Java 15+ ka best kept secret!🤯 ```java import java.lang.invoke.*; public class HiddenClassMagic { public static void main(String[] args) throws Throwable { MethodHandles.Lookup lookup = MethodHandles.lookup(); byte[] classBytes = getClassBytes(); // Bytecode bytes // Hidden class banayi jo reflection mein visible nahi hogi! Class<?> hiddenClass = lookup.defineHiddenClass(classBytes, true).lookupClass(); MethodHandle mh = lookup.findStatic(hiddenClass, "secretMethod", MethodType.methodType(void.class)); mh.invoke(); // ✅ Chalega but Class.forName() se nahi milegi! } } ``` Secret: Hidden classes reflection mein visible nahi hoti, par perfectly work karti hain!💀 --- Post 2: Java ka "Thread Local Handshakes" ka JVM level magic!🔥 ```java public class ThreadHandshake { static { // JVM internally sab threads ko pause kiye bina // single thread ko stop kar sakta hai! // Ye Java 9+ mein aaya for better profiling // -XX:ThreadLocalHandshakes=true } } ``` Internal Use Cases: · Stack sampling without stopping all threads · Lightweight performance monitoring · Better garbage collection Secret: JVM ab single thread ko individually manipulate kar sakta hai! 💡 --- Post 3: Java ka "Contended" annotation for false sharing prevention!🚀 ```java import jdk.internal.vm.annotation.Contended; public class FalseSharingFix { // Ye do variables different cache lines mein store honge! @Contended public long value1 = 0L; @Contended public long value2 = 0L; } ``` JVM Option Required: ``` -XX:-RestrictContended ``` Performance Impact: Multi-threaded apps mein 30-40%performance improvement! 💪 --- Post 4: Java ka "CDS Archives" - Application startup 10x faster!🔮 ```java // Kuch nahi karna - bas JVM options use karo: // Dump CDS archive: // -Xshare:dump -XX:SharedArchiveFile=app.jsa // Use CDS archive: // -Xshare:on -XX:SharedArchiveFile=app.jsa ``` Internal Magic: · Pre-loaded classes shared memory mein · Startup time dramatically kam · Memory footprint reduce Result: Spring Boot apps 3-4 seconds se 400-500ms startup!💀 ---
To view or add a comment, sign in
-
💾 Heap vs Stack Memory in Java — Simplified! 🚀 In Java, memory is divided into two key areas — Heap and Stack. Understanding their roles helps you write efficient and bug-free code. 💡 🧠 Stack Memory: ➡️ Used for storing method calls and local variables. ➡️ Memory is automatically managed — created when a method starts, destroyed when it ends. ➡️ Fast and follows LIFO (Last In, First Out). ➡️ Example: int x = 10; 🔥 Heap Memory: ➡️ Used for storing objects and instance variables. ➡️ Managed by Garbage Collector (GC). ➡️ Slower but more flexible — data persists beyond method calls. ➡️ Example: Student s = new Student(); 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. Example Program: class Student { String name; // stored in Heap int age; // stored in Heap Student(String name, int age) { this.name = name; this.age = age; } } public class MemoryExample { public static void main(String[] args) { int marks = 95; // Stored in Stack (local variable) // Object stored in Heap, reference 's1' stored in Stack Student s1 = new Student("Akash", 22); System.out.println("Name: " + s1.name); System.out.println("Age: " + s1.age); System.out.println("Marks: " + marks); } } ✅ Program Output: Name: Akash Age: 22 Marks: 95 💡 Explanation: The Student object is created in Heap memory with values "Akash" and 22. The reference variable s1 (which points to that object) is stored in Stack memory. The local variable marks is also in the Stack. When main() finishes execution: The Stack frame is cleared automatically. The Student object in the Heap remains until the Garbage Collector removes it. 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. #Java #Programming #MemoryManagement #JavaDeveloper #CodingTips
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