Problem Statement

Pattern:


Solution

public String longestCommonPrefix(String[] strs) {
	int limit = strs[0].length()-1; String prev = strs[0];
	for (int i = 1 ; i < strs.length ; i++) {
		int j = 0; String curr = strs[i];
		while(j < prev.length() && j < curr.length() && j <= limit && prev.charAt(j) == curr.charAt(j)) j++;
					   
		limit = j-1;
		prev = curr;
	}
	return strs[0].substring(0, limit+1);
}

TC : SC :

Notes

  • elementary my dear shit head