Shortest Way to Form String

Поделиться
HTML-код
  • Опубликовано: 9 ноя 2024

Комментарии • 83

  • @KevinNaughtonJr
    @KevinNaughtonJr  4 года назад +19

    IS IT JUST ME OR DO I LITERALLY LOOK LIKE A GIANT SITTING AT THIS DESK???
    instagram: instagram.com/kevinnaughtonjr/
    twitter: twitter.com/kevinnaughtonjr
    merch: teespring.com/stores/kevin-naughton-jrs-store
    patreon: www.patreon.com/KevinNaughtonJr

    • @Archcorsair
      @Archcorsair 4 года назад

      Yes.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад

      Daniel S ok so it’s not just me

    • @surendra9935
      @surendra9935 4 года назад +2

      We are with you too dude

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад +1

      Surendra hahaha

    • @saumya1singh
      @saumya1singh 4 года назад +3

      @@KevinNaughtonJr RUclips showing "You can not donate in this country or region?" 🤔

  • @somasishsahoo
    @somasishsahoo 4 года назад +2

    Hi Kevin,
    Appreciate all your efforts in making these videos. Have cleared a lot of my doubts.
    Regarding this algo. I can say that one of the case is missing.
    Inner while loop has to be broken if char are mismatch.
    Example - Source - "pabc" , Target - "abcpbc" - O/P - 3 but above program o/p is 2
    a break statement will resolve this.
    Thanks
    Som

  • @ShaliniNegi24
    @ShaliniNegi24 4 года назад +1

    Such an elegant solution it is!
    Thanks for the videos

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад +2

      Shalini Negi anytime! If you like my explanations be sure to sign up for the interviewing service I created thedailybyte.dev/?ref=kevin I recommend joining a premium tier if you can!

    • @ShaliniNegi24
      @ShaliniNegi24 4 года назад

      @@KevinNaughtonJr sir, Surely I will try.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад +1

      Shalini Negi amazing can’t wait to see you join :)

  • @rmadhavmca1
    @rmadhavmca1 4 года назад +3

    thanks for adding videos frequently. I really appreciate it.

  • @tusharmarda295
    @tusharmarda295 4 года назад +1

    Worst case time complexity can be improved to O(sourcelength + targetlength * log(sourcelength)), though not required for such small input sizes.
    First you create a map from char in source to a sorted array of indices in source where that char occurs. This will take one scan of source. Then, while forming substrings, you can directly use binary search on the array of the character you are trying to insert into the substring.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад

      Nice!

    • @jkrw3540
      @jkrw3540 4 года назад

      good, I had the same solution in my mind, BTW, how to do that if this time we can concatenate substrings and not subsequences?

  • @aliara1568
    @aliara1568 4 года назад

    def shortestWay(source: str, target: str) -> int:
    res = 0
    i = 0
    while i < len(target):
    exists = False
    for j in range(len(source)):
    if i < len(target) and source[j] == target[i]:
    exists = True
    i +=1
    if not exists:
    return -1
    res +=1
    return res
    source = "xyz"
    target = "xzyxz"
    shortestWay(source, target)

  • @sabisyed
    @sabisyed 3 года назад +1

    can be done in linear time. Create a map of char to integer of source. Then check target's character appear in map and do not update your counter as long as character of target string is always appearing at > prevIndex +1 .
    private int formString(String source, String target) {
    if(source.isEmpty()) {
    return -1;
    }
    Map charMap = new HashMap();
    for(int i = 0; i < source.length(); i++) {
    charMap.put(source.charAt(i), i);
    }
    int count = 0;
    int countSubString = 0;
    int index = -1;
    boolean MultiCharacterSubsequenceBeingBuilt = false;
    int lengthOfSubSequence = 1;
    for(int i = 0; i < target.length(); i++) {
    if(charMap.get(target.charAt(i)) == null) {
    return -1;
    }
    int mapIndex = charMap.get(target.charAt(i));
    count++;
    if(index == -1) {
    index = mapIndex;
    } else if(index > mapIndex -1) {
    index = mapIndex;
    MultiCharacterSubsequenceBeingBuilt = false;
    count = count - (lengthOfSubSequence - 1);
    lengthOfSubSequence = 1;
    }
    else if(index 1) {
    count = count - (lengthOfSubSequence - 1);
    }
    return count;
    }

  • @AshokBathini
    @AshokBathini 4 года назад +5

    @All-
    How about this? I felt this is easier to understand. Do u see any bugs in this code?
    T: O(target.length + source.length)
    S: O(1) = space for 26 ints to store indexes of all characters.
    Note: assumes no duplicates in source string.
    public static int countSubsequences(String s, String t) {
    if (s == null || t == null || s.length() == 0 || t.length() == 0)
    return 0;
    //maintain indexes of all characters of source
    int[] spos = new int[26];
    for (int i = 0; i < s.length(); i++) {
    spos[s.charAt(i) - 'a'] = i;
    }
    int prevPos = -1;
    int count = 0;
    for (int i = 0; i < t.length(); i++) {
    int pos = spos[t.charAt(i) - 'a'];
    //if the current character in target is out of sequence, then it's a fresh beginning of another sequence.
    if(pos

    • @renetchi
      @renetchi 3 года назад

      Maybe need to store array of array for spos since the source length can be 0-1000

    • @lazzuuu21
      @lazzuuu21 2 года назад

      What if the source contains a same character? like "aab" and the target is "aaa"? the answer would be 2, but your answer will return 3(?)

  • @idemchenko-js
    @idemchenko-js 4 года назад +1

    Hey Kevin, you've listened to your audience, no candles this time :) people were getting nervous :) Thanks for your videos, you're doing a great good!

  • @raviapiit
    @raviapiit 4 года назад

    I think, we don't need StringBuilder, because that was just being used for retrieving subsequence length. This will improve overall performance IMHO. Btw, great work. :)

  • @kumarc4853
    @kumarc4853 3 года назад

    looks like this can have constant space by using a counter rather than a builder. TThank you for the video.

  • @bdc225
    @bdc225 4 года назад +4

    Good stuff again man 🤝

  • @dipteshsil9299
    @dipteshsil9299 4 года назад +2

    Was wondering if we need the subsequence string. We can avoid that. That way we will be able to improve efficiency.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 года назад

      I think we need it cuz otherwise how do we remember what character we're gonna take on each iteration?

    • @dipteshsil9299
      @dipteshsil9299 4 года назад

      @@KevinNaughtonJr we can simply use the j variable. not reset to 0. line 5 reset to while( j < target.length() )

    • @jasminegeorge1149
      @jasminegeorge1149 4 года назад

      @@KevinNaughtonJr Here is the code without using subsequence, we can keep track using only j
      while(j

    • @ozgurgonen9061
      @ozgurgonen9061 4 года назад

      yup, just uses the length() method, so an int "len" would be enough

  • @anandprakash4995
    @anandprakash4995 4 года назад +1

    You are Awesome ! Crystal clear explanation !! learnt a lot !!

  • @divyanshukr
    @divyanshukr 4 года назад +11

    Hey Kevin, can we also do this in O(m log n) time? I am thinking we can keep a sorted list of positions of each char in source( O(n) time and O(n) space, preprocessing). Then for each char in target, we just have to find the same char's next greater position in source (greater than the index we found in source for the previous char of target). Since each char's index list is sorted, this can be done in log n time. Therefore, m chars in target and for each char log n search time = O (m log n).

    • @vaibs1001
      @vaibs1001 4 года назад +2

      Thought of the same, here is the code for it :
      int shortestWay(string source, string target) {
      int sourceLen = source.length();
      int targetLen = target.length();
      vector srcCharPos(26, vector());
      int minSub = 1;
      for (int i = 0; i < sourceLen; ++i) {
      srcCharPos[source[i] - 'a'].push_back(i);
      }
      int prevCharIndex = -1, j = 0;
      while (j < targetLen) {
      int charIndex = target[j] - 'a';
      auto it = std::upper_bound(srcCharPos[charIndex].begin(), srcCharPos[charIndex].end(), prevCharIndex);
      int index = it - srcCharPos[charIndex].begin();
      if (index >= srcCharPos[charIndex].size()) {
      if (prevCharIndex == -1)
      return -1;
      minSub++;
      prevCharIndex = -1;
      } else {
      prevCharIndex = srcCharPos[charIndex][index];
      ++j;
      }
      }
      return minSub;
      }

  • @jaatharsh
    @jaatharsh 10 месяцев назад

    awesome well explained, thanks buddy

  • @casual_chess
    @casual_chess 4 года назад +3

    Thank you for these videos sir❤

  • @prakad97
    @prakad97 4 года назад +1

    Nice.. appreciate the regular uploads man..!!

  • @VilliSopuli
    @VilliSopuli 3 года назад +1

    Do you think it would work / be any faster to have a Hashmap mapping all the characters in the source mapping to a list of integers (indices they appear at)? So they idea would be that instead of always looping thru the whole source string char by char, just looping through the occurrences of the chars and forming the subsequence starting from those indices and calculating their length and then comparing and using the longest subsequence and then moving on to the next remaining. I wasn't able to see this problem since I'm not a premium anymore.

  • @TheRaviraaja
    @TheRaviraaja 3 года назад

    will binary search on target string will help in reducing time complexity. O(nm) is very high

  • @ChocolateMilkCultLeader
    @ChocolateMilkCultLeader 4 года назад +5

    so when you do charAt(i++) it first evals charAt(i) and then increments i?

  • @renetchi
    @renetchi 3 года назад

    How about storing the source as hashmap and then looping all target, if current target is in source hashmap then continue to next target. If current target location in source is smaller than prev one then add the total count

  • @JSDev776
    @JSDev776 3 года назад

    so this is basically the greedy approach, match the longest sequence possible and repeat, but can there be a situation where you need to stop before matching further down and match from start again?

  • @Mai_Bharatwaasi
    @Mai_Bharatwaasi 3 года назад

    Thanks a lot Kevin!! you are doing great :)

  • @surepasu
    @surepasu 4 года назад

    I think the solution not working for below test cases..please correct me if I am wrong
    For this scenario it should return -1 , but returning 2
    # sourcestr = 'abc'
    # targetstr = 'abcbc1'
    For this scenario it should return 3
    , but returning 2...
    sourcestr = 'adbcklm'
    targetstr = 'aklmbc'

    • @Brodskyb523
      @Brodskyb523 3 года назад

      For your first test case, the problem states that "Both the source and target strings consist of only lowercase English letters from 'a'-'z'." So, your input should not contain the number "1".
      For your second test case, it should in fact return 2, not 3. This is because of the following: "aklm" + "bc". On the first pass, you can take "aklm" because they are in that order in the source, and then when you have to check the source a second time, you get the "bc".

  • @raviashwin1157
    @raviashwin1157 4 года назад

    what was that song played at the beginning of the video?

  • @zn4798
    @zn4798 3 года назад +1

    Brute force TLE!

  • @surendra9935
    @surendra9935 4 года назад +2

    Thank you Kevin. I pinged you in instagram to make a motivational video. love 💙 you and your videos. Take Care 😃

  • @scnullois
    @scnullois 4 года назад

    This is decent approach but you can probably do better by factoring out the section that finds the largest subseq into a dynamic programming problem which memoizes the sub-problems.

  • @charan775
    @charan775 4 года назад +1

    wow thanks for the video. but these are premium questions right? you uploading them isn't a problem?

  • @faraz7409
    @faraz7409 4 года назад

    my man! thanks for the vid very helpful!

  • @ShivamGupta-dm7kf
    @ShivamGupta-dm7kf 3 месяца назад

    I want your song playlist pls

  • @sharkk2979
    @sharkk2979 3 года назад

    How u come up with a solution? I am binge watching ur videos.

  • @gnanyreddy3030
    @gnanyreddy3030 2 года назад

    same idea efficient implementation
    int shortestWay(string source, string target) {
    int m = source.size();
    int n = target.size();
    int i=0, j=0;
    bool found = false;
    int res = 0;
    while (j

  • @chrisy.703
    @chrisy.703 2 года назад

    excellent greedy method

  • @godismygeneral
    @godismygeneral 4 года назад

    Hey Kevin what is the runtime of this algo?

    • @utalmighty
      @utalmighty 3 года назад +1

      Probably O(nm)
      n length of source
      m length of target

  • @vaishali874
    @vaishali874 4 года назад

    can we use a subsequence more than once?

  • @zhakaske5671
    @zhakaske5671 4 года назад +1

    It doesn't work for s="abcd" and t="adcb", answer must be 4, and not 3, you need to adjust the inner loop to break when there is mimatch.

    • @Brodskyb523
      @Brodskyb523 3 года назад +2

      That's wrong. It should be 3:
      "ad" + "c" + "b"

  • @harsha2s2udupa
    @harsha2s2udupa 4 года назад +3

    I think this would fail if the source string is "abcabcd" and target is "abcd" .

    • @ShaliniNegi24
      @ShaliniNegi24 4 года назад

      I was also thinking of this test case :/

    • @ShaliniNegi24
      @ShaliniNegi24 4 года назад

      For even this case also
      source: "dfed"
      target: "fed"

    • @-harshayadav
      @-harshayadav 3 года назад

      @@ShaliniNegi24 why will it fail? i guess it works perfeclty fine

  • @abhinavgupta750
    @abhinavgupta750 3 года назад

    Can source have character duplication?

  • @shriharikulkarni3986
    @shriharikulkarni3986 2 года назад

    TC is O(mn), not accepted in interview.. Can you please post O( n log m ) explanation

  • @sureshchaudhari4465
    @sureshchaudhari4465 2 года назад

    with due respects sir why i am stuck while forming logics for such questions kindly help

  • @vk1618
    @vk1618 4 года назад

    Check alternate soln

  • @rahulshrivastava3040
    @rahulshrivastava3040 4 года назад

    Kevin, Is there a lot of value in going through your videos or any tech interview videos, knowing that current situation will halt all hiring. Do not get me wrong, your videos are fantastic.

  • @krishnamohansharma8859
    @krishnamohansharma8859 4 года назад

    Put the code on your github. It's nowhere to be found

  • @pratikchowdhury9210
    @pratikchowdhury9210 4 года назад

    Lol that 1 dislike wonder why