Longest Common Prefix Java Solution

🚀 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

To view or add a comment, sign in

Explore content categories