Skip to main content

Command Palette

Search for a command to run...

Strings - Longest Common Prefix

Published
1 min read
Strings - Longest Common Prefix
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/description/

My approach:

  1. I sorted the array in the ascending order of the string sizes.

  2. Then I checked every character of the arr[0] with others strings.

  3. If they all have that character then I'll add it to my 'ans'.

  4. The moment they don't match I'll return the ans (initiliaze ans = "").

Code:

Using Sorting:

bool comp(string a, string b){
    return a.size()<b.size();
}

class Solution {
public:

    string longestCommonPrefix(vector<string>& arr) {

        sort(arr.begin(), arr.end(), comp);

        string ans = "";

        int n = arr.size();
        int m = arr[0].size();

        for(int i=0;i<m;i++){
            char ch = arr[0][i];

            for(int j=1;j<n;j++){
                if(arr[j][i]!=ch){
                    return ans;
                }
            }

            ans += ch;
        }
        return ans;
    }
};

DSA prep

Part 19 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Remove Outermost Parentheses

Remove Outermost Parentheses Problem Link: https://leetcode.com/problems/remove-outermost-parentheses/description/ Solution: Using Stack: We will use the algorithm similar to find valid paranthesis: Create a stack Push s[0] Declare an 'ind' variab...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.