"🚀 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
"Java LeetCode Challenge: Summary Ranges Problem"
More Relevant Posts
-
"🚀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
-
-
" 🚀 Day 45 of 50 – Java LeetCode Challenge " Today’s challenge was “56. Merge Intervals” — a classic array and sorting problem that sharpens your understanding of interval manipulation and greedy algorithms. The goal is to merge all overlapping intervals into distinct non-overlapping ranges. ⏱ Today’s Task – Merge Intervals 📝 Problem Statement: You are given an array of intervals where each interval is represented as [start, end]. Your task is to merge all overlapping intervals and return an array of the merged non-overlapping intervals. 🧪 Examples: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] ✅ Explanation: [1,3] and [2,6] overlap, so they merge into [1,6]. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] ✅ Explanation: [1,4] and [4,5] are overlapping. Input: intervals = [[4,7],[1,4]] Output: [[1,7]] ✅ Explanation: Sorted first, then merged into one continuous interval. 🔧 Constraints: 1 <= intervals.length <= 10⁴ intervals[i].length == 2 0 <= start ≤ end ≤ 10⁴ 💻 My Java Solution: import java.util.*; class Solution { public int[][] merge(int[][] intervals) { if (intervals.length == 0) return new int[0][]; Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); List<int[]> result = new ArrayList<>(); int[] current = intervals[0]; result.add(current); for (int[] interval : intervals) { if (interval[0] <= current[1]) { current[1] = Math.max(current[1], interval[1]); } else { current = interval; result.add(current); } } return result.toArray(new int[result.size()][]); } } 🔍 Takeaways: ✅ Smart use of sorting to arrange intervals by start time ✅ Use of greedy merging to efficiently combine overlapping ranges ✅ Clean and efficient O(n log n) time complexity due to sorting ✅ Handles all edge cases including adjacent and nested intervals 💡 Core Concepts: 📘 Sorting arrays with custom comparators 📘 Interval overlap detection 📘 Greedy algorithms and array manipulation 🎯 Day 45 completed — 5 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #Sorting #GreedyAlgorithm #JavaProgramming #Day45 #CodeNewbie #LearnInPublic
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
-
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
-
🚀 Today I Deepened My Understanding of Strings in Java Today, I explored the differences between String, StringBuffer, and StringBuilder classes in Java — focusing on mutability, performance, and thread safety. 🔹 1️⃣ String (Immutable) Strings in Java are immutable — once created, they cannot be modified. Every modification creates a new String object. Thread-safe: Yes (due to immutability) Performance: Slower for frequent modifications Common Methods: length(), charAt(), substring(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), indexOf(), startsWith(), endsWith(), replace(), split() 🔹 2️⃣ StringBuffer (Mutable & Thread-Safe) Used when frequent string modifications are required. Mutable: Can be modified without creating new objects. Thread-safe: Yes (methods are synchronized) Performance: Slower compared to StringBuilder due to synchronization overhead. Common Methods: append(), insert(), replace(), delete(), reverse(), capacity(), ensureCapacity(), setCharAt() 🔹 3️⃣ StringBuilder (Mutable & Non-Thread-Safe) Similar to StringBuffer, but not synchronized, hence faster. Thread-safe: No Best for: Single-threaded environments. Performance: Faster than StringBuffer Methods: Same as StringBuffer 🔹 4️⃣ Conversion Between Types Immutable → Mutable: StringBuffer sb = new StringBuffer(str); StringBuilder sbl = new StringBuilder(str); Mutable → Immutable: String str = sb.toString(); 🔹 5️⃣ String Tokenization I also explored string splitting techniques in Java: split() Method: Modern and efficient; uses regex. StringTokenizer Class: Older and slower; uses more memory. Example: String s = "Java is powerful"; String[] parts = s.split(" "); // Preferred modern approach import java.util.StringTokenizer; // StringTokenizer StringTokenizer st = new StringTokenizer("Java is powerful"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } 💡 Final Insight Understanding how Java handles string operations — from immutability to synchronization — is crucial for writing efficient and thread-safe code. #Java #LearningJourney #SoftwareDevelopment #StringHandling #CodingInJava #JavaDeveloper
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