🚀 LeetCode Practice – Longest Common Prefix (Java) Continuing my DSA practice series, today I solved the Longest Common Prefix problem. 📌 Problem Statement Write a function to find the longest common prefix among an array of strings. If there is no common prefix, return an empty string "". Example: Input - ["flower","flow","flight"] Output - "fl" 💡 Optimized Approach (Sorting Trick) Key Idea: If we sort the array of strings, the strings with the most differences will move to the first and last positions. So the longest common prefix of the entire array must be the common prefix between the first and last string. Example: Original: ["flower","flow","flight"] After sorting: ["flight","flow","flower"] Now we only compare: first = "flight" last = "flower" Common prefix: f ✔ l ✔ i ✖ Result:- "fl" 💻 Java Code import java.util.Arrays; class Solution { public String longestCommonPrefix(String[] strs) { StringBuilder s = new StringBuilder(); Arrays.sort(strs); char first[] = strs[0].toCharArray(); char last[] = strs[strs.length - 1].toCharArray(); for(int i = 0; i < first.length; i++){ if(first[i] != last[i]){ break; } else { s.append(first[i]); } } return s.toString(); } } ⚡ Time Complexity - O(n log n) Because we sort the array. ⚡ Space Complexity - O(1) 📚 Key Learning Sorting the strings allows us to reduce the comparison to only two strings instead of all strings, which simplifies the logic significantly. Consistent DSA practice helps improve problem-solving ability and coding efficiency for technical interviews. #leetcode #java #datastructures #algorithms #codingpractice #softwaredevelopment
Longest Common Prefix Java Solution
More Relevant Posts
-
Day 3 of Java with DSA Journey 🚀 📌 Topic: Guess Number Higher or Lower (LeetCode 374) 💬 Quote: "Efficiency is not about doing more; it's about eliminating what doesn't matter." ✨ What I Learned: 🔹 Binary Search Beyond Arrays: Binary Search isn’t limited to arrays — it works perfectly on a number range like [1...n]. 🔹 Working with APIs: Learned how to adapt logic based on API responses: -1 → Guess is too high 1 → Guess is too low 0 → Correct answer 🔹 Power of Efficiency: Even for a huge range (up to 2³¹ - 1), Binary Search finds the answer in ~31 steps 🤯 Compared to Linear Search → practically impossible! 🔹 Complexity: ⏱ Time: O(log n) 📦 Space: O(1) 🧠 Problem Solved: ✔️ Guess Number Higher or Lower 💡 Key Insight: This problem highlights the “Narrowing the Search Space” concept. Each step eliminates half the possibilities — that’s the magic of logarithmic algorithms ⚡ ⚡ Interview Insight (3-Way Decision Logic): Unlike boundary problems, here we deal with three outcomes: 1️⃣ 0 → Found the number (return immediately) 2️⃣ -1 → Move right = mid - 1 3️⃣ 1 → Move left = mid + 1 👉 Use while (left <= right) since the target is guaranteed to exist. 🔑 Takeaway: Consistency beats intensity. Showing up daily is what builds mastery. #DSA #LeetCode #Java #CodingJourney #BinarySearch #ProblemSolving #100DaysOfCode #JavaDeveloper #Algorithms
To view or add a comment, sign in
-
-
🔥 You write Arrays.sort() in Java all the time… but do you know what actually happens behind the scenes? Most developers don’t - and the truth is way more interesting than you’d expect 👇 ⚙️ 1. Sorting Primitive Types (int, double, char…) Java fires up Dual‑Pivot QuickSort ⚡ Faster than classic QuickSort ⚡ Highly optimized for real‑world data ⚠️ Not stable - but that’s irrelevant for primitives Hidden optimizations you might’ve never noticed: • Tiny arrays → switches to Insertion Sort • byte, short, char → may use Counting Sort for blazing speed 🧩 2. Sorting Objects (String, Integer, custom classes) Java switches to the legendary TIMSORT (yes, the same one Python uses) Why it’s brilliant: ✔ Hybrid of Merge Sort + Insertion Sort ✔ Detects natural order in your data ✔ Stable — crucial for objects ✔ Worst case: O(n log n) This is why object sorting feels surprisingly fast even on messy datasets. 🚀 3. Sorting Big Arrays? Java Goes Parallel Arrays.parallelSort() taps into the Fork/Join framework ✔ Splits the array ✔ Sorts chunks in parallel ✔ Merges everything efficiently A huge win for 10k+ elements on multi‑core systems. 🧠 The Cool Part Java doesn’t rely on one “universal” algorithm. It adapts intelligently based on: • Data type • Array size • Hardware • Real‑world patterns That’s why a single line of code can deliver such impressive performance. 🎯 Why This Matters Understanding this helps you: • Write more efficient, predictable code • Choose between sort() and parallelSort() • Stand out in interviews • Appreciate the engineering behind everyday APIs 💬 Did you already know Java uses multiple algorithms internally - or is this a new discovery for you? #Java #Algorithms #SoftwareEngineering #Backend #CodingInterview #ProgrammingInsights
To view or add a comment, sign in
-
"async" is one of those concepts that looks similar across languages… until You look under the hood. Lately, I have been exploring how different languages handle async. At first glance, the answer seems simple: - Use async/await, threads, or some concurrency feature. But the deeper I go, the more I realise this: The syntax may look familiar, but the execution model underneath can be completely different. For example: - JavaScript uses an event loop with non-blocking I/O - Python uses asyncio for cooperative asynchronous programming - Java often relies on threads, executors, and reactive models - Go uses goroutines to make concurrency lightweight - C# provides a very mature Task-based async/await model All of them are trying to solve a similar problem: "How do we handle more work efficiently without blocking everything?" But the way they solve it changes a lot: - How does code feel to write - How systems scale - How errors behave - How debugging feels - How much complexity does the developer have to manage That is what makes backend engineering so interesting to me. Two languages can support “async,” but the model underneath can shape performance, scalability, developer experience, and even architecture decisions in very different ways. That is also why learning only syntax is never enough. - Knowing how to write async code is useful. - Knowing how it actually runs is what helps us design better systems. The more I learn, the more I feel this: "Good engineers do not stop at syntax." "They stay curious about the runtime model underneath." #SoftwareEngineering #AsyncProgramming #BackendDevelopment #Programming #SystemDesign #JavaScript #Python #Java #Go #CSharp
To view or add a comment, sign in
-
🚀 Deep Dive into Java String Algorithms: From Basics to Palindromes I recently wrapped up an intensive session focused on mastering String manipulation in Java, specifically focusing on substrings and algorithmic problem-solving. It was a powerful reminder that complex problems become simple when you break them down into smaller, manageable parts. Here are the key takeaways from the session: 🔹 Subarrays vs. Substrings: One of the most important realizations was that the logic for printing all subarrays and substrings is essentially the same. The transition from handling primitive arrays to String objects is seamless once you understand how to manage indices using loops and s.charAt(). 🔹 Algorithmic Efficiency: We explored how to find the Longest Palindromic Substring by: Breaking down the problem: First, ensure you can print every possible substring. Optimizing the search: Reversing the size loop allows you to find the longest potential candidate first. Two-Pointer Palindrome Check: Implementing a check using two indexing variables (i and j) to compare characters from both ends without the overhead of reversing the string. 🔹 Debugging & Exceptions: We had a fascinating discussion on StringIndexOutOfBoundsException. A key insight was how the way you write your code—such as storing a value in a variable versus printing it directly—can determine exactly when and how an exception is triggered during execution. 🔹 Practical Application: Beyond theory, we implemented logic to: Find if one string is a contiguous substring of another. Count occurrences of a specific substring within a larger text. Handle case sensitivity using equalsIgnoreCase() for more robust comparisons. The Road Ahead: The session concluded with a "six-output" challenge—a complex assignment requiring us to reverse individual words in a sentence, count character lengths, and manipulate sentence structures (e.g., "India is my country"). As we move into a short break, the goal is clear: consistency. Whether it's five hours of deep practice or solving just two problems on the worst of days, staying in touch with the code is what builds mastery. #Java #Coding #SoftwareDevelopment #Algorithms #DataStructures #LearningJourney TAP Academy
To view or add a comment, sign in
-
-
Embabel treats LLMs as participants in strongly typed workflows — not black boxes — and the Spring creator Rod Johnson spring says that gives Java developers an edge Python can't match. By Darryl Taft
To view or add a comment, sign in
-
GitVoyant v0.3.0. Temporal code intelligence now runs across Python, JavaScript, Java, and Go. Four language-specific analyzers behind a single protocol. Tree-sitter for unified AST parsing. Automatic language detection. Static analysis tells you a file is complex. GitVoyant tells you whether that complexity is growing, shrinking, or stable, and at what rate. https://lnkd.in/g4fNbdRg
To view or add a comment, sign in
-
𝐂𝐚𝐧 𝐰𝐞 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐞 𝐭𝐡𝐞 "𝐦𝐚𝐢𝐧()" 𝐦𝐞𝐭𝐡𝐨𝐝 𝐢𝐧 𝐉𝐚𝐯𝐚? In my previous post, we discussed that the "main()" method is static. No — we cannot override the "main()" method Why ? Because "main()" is static. And we cannot override static methods And in Java: 📃Overriding happens at runtime ⏱️ 📃 It depends on objects 👤 But ❌ Static methods belong to the class ❌ They are loaded during class loading time (before objects are created) 🔍𝐖𝐡𝐚𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐭𝐡𝐞𝐧? You can write a main() method in a child class ❌ But it does not override the parent’s main(). It’s called "𝐌𝐞𝐭𝐡𝐨𝐝 𝐇𝐢𝐝𝐢𝐧𝐠". 𝐜𝐥𝐚𝐬𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧"); } } 𝐜𝐥𝐚𝐬𝐬 𝐂𝐡𝐢𝐥𝐝 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧"); } } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐏𝐚𝐫𝐞𝐧𝐭 𝐩 = 𝐧𝐞𝐰 𝐂𝐡𝐢𝐥𝐝(); 𝐩.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧 𝐂𝐡𝐢𝐥𝐝.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧 } } Output : Parent main Child main ♟️These main() methods are not called automatically by the JVM — they run only when we explicitly invoke them. ♟️Only main(String[] args) is invoked automatically by JVM. Other overloaded or hidden main() methods are executed only when explicitly called. 🚀 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 "main()" method cannot be overridden because it is static — it can only be hidden #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #OOP #InterviewPrep
To view or add a comment, sign in
-
To make your first post truly engaging, you want to hook the reader with a "problem" they didn’t know they had, and then present your page as the "solution." Here is a short, punchy, and high-energy post description for your LinkedIn launch: The Ghost in the Machine 👻 Ever wonder why your Java code behaves differently under heavy load? Or why your Python backend hits a performance wall despite "clean" logic? The truth is: The code you write isn't always the code that runs. Between your syntax and the hardware lies a world of bytecode, memory management, and invisible execution layers. That is where the real bugs—and the real optimizations—hide. Welcome to The Bytecode Phantom. We’re here to deconstruct the "tricky" side of backend engineering: * 🔍 Java Internals: JVM secrets and bytecode-level logic. * 🐍 Python Mastery: Beyond the basics into the runtime core. * 🏗️ System Design: Architectural patterns that actually scale. Stop following the documentation. Start mastering the mechanics. [Follow to Decrypt the Complex] #TheBytecodePhantom #Java #Python #BackendEngineering #SystemDesign #SoftwareArchitecture #CodingSecrets
To view or add a comment, sign in
-
-
⏳ Day 21 – 1 Minute Java Clarity – Polymorphism Explained Simply 🎭 Same action… different behaviour! 🔥 📌 What is Polymorphism? 👉 “Poly” = Many 👉 “Morphism” = Forms ✔ One method behaves differently based on the object 👉 It is the core of OOP and makes code flexible & reusable 📌 Types of Polymorphism 1️⃣ Compile-Time Polymorphism 👉 Achieved using Method Overloading class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } ✔ Same method → different parameters ✔ Decided at compile time 2️⃣ Runtime Polymorphism 👉 Achieved using Method Overriding class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks!"); } } Animal a = new Dog(); a.sound(); // Dog barks! ✔ Parent reference → child object ✔ Decided at runtime 💡 Real-time Example 🎮 Game Character Same action → "attack()" Warrior → uses sword ⚔️ Archer → uses bow 🏹 Mage → casts spell 🔮 👉 Same method → different behaviour ⚠️ Interview Trap 👉 Can we achieve polymorphism without inheritance? ✔ YES (Using Method Overloading) ❌ NO (for Runtime polymorphism – needs inheritance) 💡 Quick Summary TypeMethodTimeExampleCompile-TimeOverloadingCompile Timeadd()RuntimeOverridingRuntimesound() 🔹 Why Polymorphism matters? ✔ Cleaner code ✔ Easy to extend ✔ Reduces duplication ✔ Helps in real-world system design 🔹 Next Topic → Encapsulation in Java 🔐 Which type do you find tricky — Compile-time or Runtime? Drop 👇 #Java #JavaProgramming #Polymorphism #OOPs #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Day 4 of my DSA Journey 🚀 Today’s challenge: The classic Palindrome Number problem. For today's solution, I focused on an intuitive approach using String manipulation in Java. Sometimes the best way to solve a problem is to break it down into steps that make logical sense right out of the gate! 🧠 My Approach: Handle the edge case: Negative numbers can never be palindromes, so return false immediately. Convert the integer to a String. Use a for loop to iterate backwards through the string, building a new reversed string character by character. Compare the original string with the reversed string to determine if it's a palindrome. ⚡ Key Learnings & Java Gotchas: String Iteration: In Java, strings aren't exactly like arrays, so I had to use .charAt(i) instead of standard bracket notation [i] to grab individual characters. The Comparison Trap: I learned the crucial difference between == and .equals(). In Java, == compares memory locations, but .equals() checks if the actual text values are the same. A huge "aha!" moment for handling Strings! Edge Case Handling: Always check for negative numbers first to save processing time. 📌 Complexity: Time: O(n) — where n is the number of digits, since we loop through the string once. Space: O(n) — for storing the string representations of the number. Every bug is a lesson, and every solved problem is a step forward. On to the next one! 💪 #DSA #DataStructures #Algorithms #ProblemSolving #CodingJourney #Java #TechJourney#DSAJourney #LeetCode #Coding #LearnInPublic #GrowthMindset
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