014. Longest Common Prefix

Difficulty: Easy

Frequency: N/A

Write a function to find the longest common prefix string amongst an array of strings.


My solution:
Data structure:
string, array
Steps:
Complexity:
Runtime: O(m)
Space: O(1)
Test cases:
Corner cases:
1. empty array
Code:
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string result = "";
        if (strs.size() == 0) return result;
        for (int idx = 0; idx < strs[0].size(); result += strs[0][idx], idx++) {
            for (int v_sz = 1; v_sz < strs.size(); v_sz++) {
                if(idx >= strs[v_sz].size() || strs[v_sz][idx] != strs[0][idx]) {
                    return result.substr(0, idx);
                }
            }
        }
        return result;
    }
};

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:
Advertisements

2 thoughts on “014. Longest Common Prefix

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s