Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.7 kB
4
Indexable
Never
#include<bits/stdc++.h>
using namespace std;

// time O(sum of length of all strings), space O(1)
// created by Aman Jain

// update: comments added, optmized code, removed unnecessary counter variables
// and control statements

string findCommonPrefix(vector<string> stringList) {
    int upperBound = -1, answerNotFound = 1;
    for(int i = 0; answerNotFound == 1; ++i) { // loop to increment current common index
        for(int j = 1; j < stringList.size(); ++j) { // loop to traverse all strings
            if(i >= stringList[j].size() || stringList[j][i] != stringList[0][i]) {
                // if i is out of range for current string
                // or the letter is not equal to the first string's i'th letter
                // then prefix upperBound is previous i, set answerNotFound to 0
                // which will break the outer for loop
                answerNotFound = 0;
                upperBound = i - 1;
            }
        }
    }
    // if prefix upperBound is -1, it means that there is no common prefix substring, return empty string
    // otherwise calculate the common prefix string using string::substr method and return it.
    // string::substr method takes starting index and size of the substring
    return upperBound > -1 ? stringList[0].substr(0, upperBound + 1) : "";
}

int main() {
    int n, upperBound = -1;
    bool answerNotFound = true;
    vector<string> stringList;
    cin >> n;
    for(int i = 0; i < n; ++i) {
        string str;
        cin >> str;
        stringList.push_back(str);
    }
    string answer = findCommonPrefix(stringList);
    cout << "common prefix substring is : " << answer << endl;
    return 0;
}