Longest Common Prefix in Array of Strings

Day - 34 Longest Common Prefix The problem - Write a function to find the longest common prefix string amongst an array of strings. Example : strs = [“flower”,”flow”,”flight”] -> “fl” strs=[“dog”,”racecar”,”car”] -> “” Brute force - Compare all the characters at each position across the strings, but the time complexity will be O(S), S is sum of all characters and require multiple traversals. Approach Used - Horizontal Scanning •) Handle edge case: if array is null or empty, return "". •) Initialise pref = strs[0], prefLen = prefix.length(). •) while(prefLen > s.length()) or pref doesn't match the beginning of s (or prefix is longer than s) 1 - Reduce prefix length by 1 (prefLen--). 2 - If prefLen becomes 0, no common prefix exists - return "". 3 - Update prefix to pref.substring(0, prefLen). 4 - Continue to next string. •) Return the final pref. Complexity - Time - O(S), total number of characters in all strings. Space - O(1), only used variables. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories