Longest Common Prefix

แชร์
ฝัง
  • เผยแพร่เมื่อ 30 พ.ย. 2024

ความคิดเห็น • 110

  • @KevinNaughtonJr
    @KevinNaughtonJr  5 ปีที่แล้ว +59

    EVERYONE MAKES MISTAKES

    • @noushinb4671
      @noushinb4671 5 ปีที่แล้ว +3

      God bless you! (Noushin)

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว

      @@noushinb4671 I hope it was helpful Noushin!

    • @amylee8688
      @amylee8688 5 ปีที่แล้ว +1

      Hello! Thank you for your videos. It’s been super helpful. Would you be able to do “Perfect Squares” question on Leetcode? I forgot the number but it’s tagged under BFS and Dynamic Programming and is one of the most commonly asked interview questions. Thank you!

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว +2

      @@amylee8688 Anytime Amy and thanks for the suggestion I'll throw it on my list :)

    • @sandipbhaumik
      @sandipbhaumik 4 ปีที่แล้ว

      ai can help in here :)

  • @xNinjaTovarx
    @xNinjaTovarx 4 ปีที่แล้ว +2

    Yo Kevin!
    I graduated about a year ago and used many of your tutorials for the build-up to my job search, which I had landed and continue to love. I have been running through some of the things you have done since then (about June-ish of last year) while getting ready to shop around for a competitive pay increase at another company, and brother you still got it!
    First of all, thanks a bunch man. Over the course of my degree I have become a pro at scraping the entire web for tutorials, videos, deep dives and how-to's, and I can easily say that you are my top guy -- I truly hope you are making beaucoup bucks and are a senior staff-level engineer or well on your way.
    This is all a long-winded way to say that you provide all of this basically free of charge and a man's gotta eat (or buy a Spotify account to keep kicking out those sick intro tunes). I see your Patreon, but I have never liked a monthly subscription. Do you have a place for those of us who appreciate you but don't want to do a monthly subscription to donate?

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 ปีที่แล้ว +3

      Yooooo Daniel you just made my day dude :') I really appreciate you and everyone else who takes the time and leave a comment letting me know you appreciate the content I provide. I'm super happy to hear that you landed a job you love last year and I'm sure you're about to land another great gig
      I have venmo/paypal if you feel more comfortable sending money there! You can also sign up for Patreon and then cancel immediately and this way you get charged once and only once. This is my Patreon if you're interested in signing up and canceling www.patreon.com/KevinNaughtonJr, but if you want my venmo/paypal just lmk. Either way whatever you decide I appreciate you even considering donating and helping me out it means a lot to me!

    • @xNinjaTovarx
      @xNinjaTovarx 4 ปีที่แล้ว

      @@KevinNaughtonJr Venmo is my go-to if you feel comfortable posting that!

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 ปีที่แล้ว

      Daniel Tovar thanks so much dude my Venmo handle is @Kevin-Naughton-1

  • @TrollFreeInternet
    @TrollFreeInternet 5 ปีที่แล้ว +36

    Lmao the editing when u got the error made me laugh...appreciate all the work u put in making this videos buddy :)

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว

      haha thanks Pat and anytime always happy to help :')

  • @KaisarAnvar
    @KaisarAnvar 2 ปีที่แล้ว

    LOL the ending submission was hilarious! Love your videos brother. You're my inspiration.

  • @jokesta0094
    @jokesta0094 4 ปีที่แล้ว +1

    Stringbuilder instead of appending to existing string as strings are immutable. Other than that very clean

  • @hardikShruti
    @hardikShruti 3 ปีที่แล้ว

    Thanks for the solution..its a really nice and simple one... ☝️
    I tried the same problem before checking your solution...using String.startsWith() function...
    public static void main(String args[]) {
    String[] inputData = {"flying", "flyght", "flyhgt", ""};
    /*
    1. Pick the first character from the first String.
    2. Check if it's there at the begging of every String.
    3. If yes then pick the second character and check the same way.
    4. If it's not there then stop it and print the combined string as a response.
    */
    if (inputData == null || inputData.length == 0) {
    System.out.println("No data available in given input Data");
    return;
    }
    if (inputData.length == 1) {
    System.out.println("Common prefix is " + inputData[0]);
    return;
    }
    String commonPrefix = "";
    for(int i = 0;i

  • @newandroidfan
    @newandroidfan 4 ปีที่แล้ว +1

    I had the same solution, the only issue with mine was that I kept looking for the next character in the strings even after one character was not found in the rest of the strings. Your solution made me realize I didn't have to go through the strings again if one of the characters was not found. Very helpful :)

  • @ersinerdem7285
    @ersinerdem7285 3 ปีที่แล้ว +1

    a simple advice, do not convert string to char array. Reason is in java strings are stored in char arrays internally already. If you use charAt(index), it just gets the value at that index. toCharArray allocates a new char array, copies the values and returns it. There is no need to make a new char array where there is already one present.

  • @ravicrazyster
    @ravicrazyster 3 ปีที่แล้ว +1

    best and easy solution found so far

  • @Chino50863486
    @Chino50863486 5 ปีที่แล้ว +9

    Nice job, you explained this so clearly. The key part of this algorithm is the condition checking in my opinion.
    Where you checked if the index > length of word you are checking FIRST so it doesn't trigger the out of bounds exception.
    I was wondering how I could do that without a try and catch block.
    Thank you :)

  • @JackMarchetti29
    @JackMarchetti29 5 ปีที่แล้ว +6

    Probably want to use StringBuilder instead of concatenating strings. So instead of declaring the longestCommonPrefix string variable you'd declare it as a StringBuilder and just Append every "c" that matches then return that. (I think Java has StringBuilder)

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว +2

      Yeah StringBuilder would def help it be that much more efficient :)

    • @piyush12121
      @piyush12121 5 ปีที่แล้ว +3

      "+" operator, when used with String, in Java automatically gets converted into a StringBuilder by Compiler. I think they introduced this feature in Java 8 or so. Plus it makes the code look more neat and clean. So no need.

    • @JackMarchetti29
      @JackMarchetti29 5 ปีที่แล้ว +1

      @@piyush12121 that's pretty cool. i wonder if C# does this now.

    • @sahaparamjit
      @sahaparamjit 5 ปีที่แล้ว +1

      @@piyush12121 Read this www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html. Especially the conclusion.

    • @huizhao2050
      @huizhao2050 2 ปีที่แล้ว

      @@JackMarchetti29 Don't think so, C# doesn't have this feature. You still need to use a StringBuilder.

  • @wilsonwang8641
    @wilsonwang8641 2 ปีที่แล้ว +1

    If we sort the strings ascending by length at first, then we don't have to check if the index is larger than each string's length or not.
    Then we just need to iterate each char of the first string, the shortest one.
    Would't it be better and clear?

  • @nands4410
    @nands4410 4 ปีที่แล้ว

    U can preprocess and find the string with minimal length.To avoid the out of bounds issues

  • @yuhaokong
    @yuhaokong 4 ปีที่แล้ว +1

    you should probably use a string builder when you are constantly changing the string.

  • @z08840
    @z08840 3 ปีที่แล้ว

    1. sort array.
    2. find common prefix for the first and last string in the array.

  • @leanobajio
    @leanobajio 5 ปีที่แล้ว +5

    O(mn) where m is the length of strs and n is the length of the smallest string

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว +3

      Yep which in the worst case all strings are the same length :)

  • @farhanaditya2647
    @farhanaditya2647 2 ปีที่แล้ว

    Why is Amazon asking an "Easy" question?

  • @Gunit935
    @Gunit935 5 ปีที่แล้ว +2

    Thank you for explanation! You can also solve it using divide and conquer.

  • @goodwish1543
    @goodwish1543 5 ปีที่แล้ว

    Same idea, in Python.
    class Solution:
    def longestCommonPrefix(self, strs):
    res = ""
    if not strs:
    return res
    n = len(strs[0])
    for i in range(n + 1):
    for str in strs:
    if i >= len(str) or str[i] != strs[0][i]:
    res = str[:i]
    return res
    return res
    strs = ["a"]
    o = Solution()
    ans = o.longestCommonPrefix(strs)
    print(ans)

  • @abilevine4832
    @abilevine4832 4 ปีที่แล้ว +3

    I have heard about a ds called trie cant we solve this using tht????

    • @codestorywithMIK
      @codestorywithMIK 4 ปีที่แล้ว

      Yes, it can be solved using trie. construct a trie from all the words and then find the longest common prefix. You can see the details in leetcode as well for this approach. It's given there

    • @omarhosny6947
      @omarhosny6947 4 ปีที่แล้ว

      Yes sure

  • @mayankrathore7558
    @mayankrathore7558 5 ปีที่แล้ว +4

    Your all hard work, its really appreciated thanks

  • @velocityvibezzz
    @velocityvibezzz ปีที่แล้ว

    Really appreciate the solution here. Your explanations are so good that I just watch the first 3 mins and am able to code it myself :P

  • @hari10599
    @hari10599 5 ปีที่แล้ว +2

    Strings are immutable, right? How’d you concatenate then?

    • @m13m
      @m13m 5 ปีที่แล้ว +8

      Not a Java person but I think concatenate operation crates a new string

  • @RahulRaj-us1is
    @RahulRaj-us1is 2 ปีที่แล้ว

    Hi Kevin. Thanks so much for posting this explanation video. I was wondering if you could go into a bit more detail on the space complexity of this algorithm. Wouldn't this have a space complexity of O(n) where n is the size of the char array of your first for loop? Because you are appending a character to the string each time?

  • @ameyapotdar461
    @ameyapotdar461 3 ปีที่แล้ว

    The easiest solution I found for this problem,thanks for this

  • @sushantkshirsagar
    @sushantkshirsagar 4 ปีที่แล้ว

    Kevin please cover longest common subsequence problem

  • @iloveallparties
    @iloveallparties 5 ปีที่แล้ว +1

    What are your best tips for getting better? I’m a CS student graduating next semester and have taken Data Structures & Algos but I find I am constantly having to look up answers even to leetcode easy questions. I appreciate any feedback.

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 ปีที่แล้ว +17

      Just gotta keep practicing that's all it is. Start with easy questions and honestly attempt them. Take 30 minutes and try to solve the question on your own without looking at other resources for help. Eventually, easy problem won't be that hard anymore and you can move onto harder problems and do the same thing. Also when you do have to look at a solution, make sure you understand it before moving on the next question, ideally, every question you attempt or review you'll learn something from to apply to other problems. Hope these tips are helpful!

    • @iloveallparties
      @iloveallparties 5 ปีที่แล้ว

      Great advice, thank you. How many leetcode questions would you say is a good amount to practice a day?

    • @mujtabahussain7015
      @mujtabahussain7015 2 ปีที่แล้ว

      @@iloveallparties hey brother how's life going? -junior(first year student)

  • @RohanDaDev
    @RohanDaDev 4 ปีที่แล้ว +2

    Holy shit thats some good performance lol

  • @iDanceWithNoPants
    @iDanceWithNoPants 4 ปีที่แล้ว

    Am I missing something? Since you loop through the first string to check for prefix based on that string only, wouldn’t an input of [dog, race, racer] fail? Since it uses dog to check but the longest prefix is race

    • @khyatiseth6199
      @khyatiseth6199 4 ปีที่แล้ว

      The longest common prefix has to be present in all the strings of the strs array. How is race the longest prefix when it is not present in dog ? Hence, the longest common prefix is an empty string here.

    • @kishalaybhattacharya8312
      @kishalaybhattacharya8312 2 ปีที่แล้ว

      @@khyatiseth6199 what about [flow, flower, dog]? It should be an empty string too, but seems like it will return flow. Please correct me if I am wrong

  • @beyond-convention
    @beyond-convention 4 ปีที่แล้ว

    Great video !! It will be great if you can also explain the time and space complexity

  • @gazm9c
    @gazm9c 4 ปีที่แล้ว

    Thanks for the vid
    My solution was exactly the same as yours but when I checked solutions offered by Leetcode I realized that my algo is not the fastest possible
    Is this kind of solution enough to pass the interview(on Amazon for example) or you have to present some improvements for it?

  • @BrendanMetcalfe
    @BrendanMetcalfe 4 ปีที่แล้ว

    Didn't fully understand what index represents and how you're comparing

  • @adityamandlekar751
    @adityamandlekar751 4 ปีที่แล้ว

    wouldnt it helpful to find out minimum length string and use that as a base while comparing each characters in other strings ??

  • @k.alipardhan6957
    @k.alipardhan6957 5 ปีที่แล้ว

    if you haven't done this question already, could you please consider it. its from a google online SWE internship test, about 6 months ago:
    Assume you are given a tree of N nodes. The nodes are numbered from 0 to N-1 and their parents are represented in an array A, such that A[i] denotes the number of the parent of the i-th node. Node 0 is the root node and it will not have a parent, so the corresponding value in array A will be -1. We define the distance between two nodes to be the length of the shortest path between them, and we define an ancestor of the i-th node as any node lying on the shortest path between the i-th node and the root. Your goal is to find the ancestor at distance D of every node of the tree.

    • @k.alipardhan6957
      @k.alipardhan6957 5 ปีที่แล้ว

      also, here is another suggestion, this one is from demonware (might be too long; only a suggestion):
      You have a long piece of text, and you want to send it to your friend as a series of SMS messages. Your text consists of English letters (uppercase and lowercase) and spaces. The text doesn't contain any leading spaces at the beginning or trailing spaces at the end. There are no two consecutive spaces in the text. One proper SMS can contain at most K characters. If the text is longer, it needs to be split into parts. Each part should be sent in a separate message that fulfills the maximum length requirement. Text may not be split within words. The order of the words and the messages can't change, so that we can later concatenate the resulting messages to retrieve the original text. Spaces at the start and end of all messages are removed, and thus are not accounted for in the overall message length. The goal is to count the number of SMS messages needed to accommodate the whole text, keeping the length of each message less than or equal to K. The total number of SMS messages must be kept to a minimum, however; it would not be acceptable, for example, to take the wasteful approach of programmatically sending one SMS for each word in the original text! Write a function: int solution(char *S, int K); that, given a string S representing the text that needs to be split and an integer K that is equal to the maximum possible message length, returns the number of SMS messages needed. For instance, given string S="SMS messages are really short" and K = 12, your function should return 3. You could split this text into proper messages as follows: "SMS" "messages are" "really short" If it's impossible to split text into proper SMS messages, your function should return −1. Assume that: K is an integer within the range [1..500]; S is a non-empty string containing at most 500 characters: only letters and spaces, there are no spaces at the beginning and at the end of S; also there can't be two or more consecutive spaces in S. In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

  • @abcdeereijgfhd3215
    @abcdeereijgfhd3215 3 ปีที่แล้ว +4

    that was a funny thing that u could not pass the code 3 times. Made me laugh! BTW excellent lecture~! keep going~!

    • @litinr6321
      @litinr6321 3 ปีที่แล้ว

      th-cam.com/channels/rvpRH4lSRjp2T6btl0lf4w.html try this too.. leetcode solutions...java interview questions

  • @meharkaur7326
    @meharkaur7326 4 ปีที่แล้ว +2

    This was so clear and concise! Thanks a lot

  • @Nobody2310
    @Nobody2310 5 ปีที่แล้ว

    Kevin, can you please do “ reverse linked list in K group” , There is no good explanation of the solution, there are solutions but a modified version where they even reverse the remaining elements, but leetcode asks to leave that as is. Thanks in advance! 😊

  • @saisanjaynagarur
    @saisanjaynagarur 4 ปีที่แล้ว

    Could we use a method os.path.conmonprefix(list of words)

  • @keeranmnc1605
    @keeranmnc1605 4 ปีที่แล้ว

    Thanks for the great videos. They're really helpful. With regards to space complexity, we have that growing longestPrefix variable that means it isn't constant space. The longer the inputs, the more memory this program will consume. So I believe the space complexity is O(m/n), where m is the number of matching characters across all words and n is the number of words in the strs array. Or we can just say O(n) where n is the number of matching characters in the prefixes.

  • @naveengupta2995
    @naveengupta2995 4 ปีที่แล้ว

    why can't we sor the string and compare first and last only
    Python Code
    commonpfefix=['GREEN','GREADE','GREET','GREAD']
    commonpfefix.sort()
    print(commonpfefix)
    n=0
    matched=""
    for ch in commonpfefix[0]:
    if ch not in [i[n] for i in commonpfefix[1:] ]:
    break
    else:
    matched=matched+ch
    n+=1
    print(matched)

  • @Fleshlight_Reviewer
    @Fleshlight_Reviewer 4 ปีที่แล้ว +1

    i enjoy the boo-ing sounds

  • @mohammadosama4709
    @mohammadosama4709 4 ปีที่แล้ว

    Can someone tell me this is most optimal or there's optimal solution using trie?

  • @ankitagarwal4914
    @ankitagarwal4914 4 ปีที่แล้ว +4

    High Coding standard!! It might be achieved through lot of practise

  • @nanug6292
    @nanug6292 4 ปีที่แล้ว

    class Solution {
    public String longestCommonPrefix(String[] strs) {
    String longestcommonprefix="";
    if(strs == null || strs.length == 0)
    {
    return longestcommonprefix;
    }
    int index = 0;
    for(char c : strs[0].toCharArray())
    {
    for(int i=1;i= strs[i].length() || c!=strs[i].charAt(index))
    {
    return longestcommonprefix;
    }

    }
    longestcommonprefix +=c;
    index++;
    }
    return longestcommonprefix;
    }

    }
    Runtime: 9 ms, faster than 14.75% of Java online submissions for Longest Common Prefix.
    Memory Usage: 38.8 MB, less than 29.74% of Java online submissions for Longest Common Prefix.
    Next challenges:

    • @nanug6292
      @nanug6292 4 ปีที่แล้ว

      i am not getting runtime as 1 ms plzz help

  • @anil4950
    @anil4950 5 ปีที่แล้ว

    can u solve using sorting

  • @coderrocks
    @coderrocks 4 ปีที่แล้ว

    Truly Awesome explanations!! the best on the internet! thank a lot

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 ปีที่แล้ว +1

      coder2701 rocks thank you!!! If you like my explanations be sure to sign up for the interviewing service I created thedailybyte.dev/?ref=kevin I’d recommend joining the annual tier if you can!

    • @coderrocks
      @coderrocks 4 ปีที่แล้ว

      @@KevinNaughtonJr sure will join whenever my pocket permits. I am pretty sure this one shall be a good investment on self and will prove beneficial

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 ปีที่แล้ว +1

      @@coderrocks It definitely will be and amazing can't wait to see you join :)

    • @coderrocks
      @coderrocks 4 ปีที่แล้ว

      @@KevinNaughtonJr Sure thing !

  • @mrbeastfannatic
    @mrbeastfannatic 4 ปีที่แล้ว

    Hey Kevin I have learnt a lot from your videos and I love them . Could you do the Longest String Chain it is commonly asked by google these days.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 ปีที่แล้ว

      Thanks and I'll see what I can do :)

  • @RG-yj4cb
    @RG-yj4cb 3 ปีที่แล้ว

    Great Work; I think the index is redundant and instead of that we could have another index-based for loop instead of range based;

    • @RG-yj4cb
      @RG-yj4cb 3 ปีที่แล้ว

      Sample:
      string longestCommonPrefix(vector& words) {
      string longestCommonPrefix = "";

      if(words.size() == 0) {
      return longestCommonPrefix;
      }

      for(int i = 0; i < words[0].size(); i++) {
      for(int j = 1; j < words.size(); j++) {
      if(i >= words[j].size() || words[0][i] != words[j][i]) {
      return longestCommonPrefix;
      }
      }
      longestCommonPrefix += words[0][i];
      }
      return longestCommonPrefix;
      }

  • @seal0118
    @seal0118 4 ปีที่แล้ว

    leetcode's solution description was frustrating to look at, even more frustrating as i try to remodel my code and nothing works, but you made it a lot easier, thany you sir !

  • @helishah7773
    @helishah7773 4 ปีที่แล้ว

    Kevin the way you explain that's really great. And the music while compiler error made me laugh. :D Anyway, You are my favorite. :) Thanks for the videos.

  • @anshul-sharma
    @anshul-sharma 4 ปีที่แล้ว

    don't know if asking for a lot, but is there a way to push code directly from leetCode to gitHub 🤞

  • @AdityaPant29
    @AdityaPant29 5 ปีที่แล้ว +3

    Appreciate the effort 👍

  • @shilparani9080
    @shilparani9080 4 ปีที่แล้ว

    Hello Kevin. First of all, Thank you so much for this guided video series for top interview questions. I really appreciate your efforts.
    Secondly, I have incorporated almost the same logic but I get 9ms, 42 MB metric. I am not sure what's going wrong here?
    class Solution {
    public String longestCommonPrefix(String[] strs) {
    String longestCommonPrefix = "";
    if(strs == null || strs.length == 0)
    return longestCommonPrefix;
    int index = 0;
    for(char ch : strs[0].toCharArray()){
    for(int i = 1; i< strs.length; i++ )
    {
    if(index == strs[i].length() || strs[i].charAt(index) != ch)
    return longestCommonPrefix;
    }
    longestCommonPrefix = longestCommonPrefix + ch;
    index++;
    }
    return longestCommonPrefix;
    }
    }

    • @DishaSaraiya_xo
      @DishaSaraiya_xo 4 ปีที่แล้ว

      I have the same question. Would be super grateful if someone could explain!

    • @nanug6292
      @nanug6292 4 ปีที่แล้ว

      yeah me too i wrote the exact same code and i am also getting the 9 ms and 40 MB metic

  • @alexshiferaw7180
    @alexshiferaw7180 4 ปีที่แล้ว

    Thank you

  • @rudra1383
    @rudra1383 4 ปีที่แล้ว

    it gives the wrong answer

  • @youssefhussien8029
    @youssefhussien8029 5 ปีที่แล้ว

    Important Hello Kevin, in this link is my attempt to solve this problem using hashmaps in C++.
    codepad.org/SUAHD1pB
    however, I stopped at a point that I can't get through, if I have for ex vector of ["aa","aa"] my count will be 4 so it will return empty string. So what should I do please respond to me

  • @TrollFreeInternet
    @TrollFreeInternet 5 ปีที่แล้ว

    Also why does amazon ask easy questions like this?i am assuming this is for phone screen interview..i don’t think they will ask such an easy question for onsite interview or do they?

    • @rafalrocks
      @rafalrocks 5 ปีที่แล้ว

      While the algo itself is quite easy, there are a couple of gotchas and/or edge cases that need to be considered for most of these questions. In this case, you want to pick the shortest string in the array as your base comparer and account for empty arrays, etc. Again, nothing hard, but can make a diff. during the actual interview under pressure

  • @db-wk8xb
    @db-wk8xb 5 ปีที่แล้ว

    in line 9 it should be stars[index] otherwise c will never change

  • @zacharykline9575
    @zacharykline9575 4 ปีที่แล้ว

    Good video and clear solution

  • @sandipbhaumik
    @sandipbhaumik 4 ปีที่แล้ว

    revision :)

  • @sachinsingh101
    @sachinsingh101 5 ปีที่แล้ว

    Incorrect solution. Consider this input -
    rowdynas
    rowpynas
    rowllbynas
    It would return "row". Where as the answer is - "ynas"

    • @Gurvinder2107
      @Gurvinder2107 5 ปีที่แล้ว +2

      ynas is a suffix not preffix

    • @LastVoyage
      @LastVoyage 5 ปีที่แล้ว +1

      Look up what a prefix is.

    • @nishantsharma3100
      @nishantsharma3100 5 ปีที่แล้ว +5

      did your teacher told you about prefix , suffix ?or did they directly started putting leetcode questions up your ass?