Shortest Way to Form String

Sdílet
Vložit
  • čas přidán 8. 07. 2024
  • For business inquiries email partnerships@k2.codes SOCIAL
    ----------------------------------------------------------------------------------------------------------------
    Instagram: / kevinnaughtonjr
    Twitter: / kevinnaughtonjr
    Patreon: / kevinnaughtonjr
    Merch: teespring.com/stores/kevin-na...
    GitHub: github.com/kdn251
    MUSIC
    ----------------------------------------------------------------------------------------------------------------
    xo bored llif3 by young frontwood
    / xo-bored-lif3
  • Věda a technologie

Komentáře • 82

  • @KevinNaughtonJr
    @KevinNaughtonJr  Před 4 lety +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

  • @rmadhavmca1
    @rmadhavmca1 Před 4 lety +3

    thanks for adding videos frequently. I really appreciate it.

  • @Mai_Bharatwaasi
    @Mai_Bharatwaasi Před 3 lety

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

  • @anandprakash4995
    @anandprakash4995 Před 4 lety +1

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

  • @idemchenko-js
    @idemchenko-js Před 4 lety +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!

  • @bdc225
    @bdc225 Před 4 lety +4

    Good stuff again man 🤝

  • @casual_chess
    @casual_chess Před 4 lety +3

    Thank you for these videos sir❤

  • @ShaliniNegi24
    @ShaliniNegi24 Před 3 lety +1

    Such an elegant solution it is!
    Thanks for the videos

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 3 lety +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 Před 3 lety

      @@KevinNaughtonJr sir, Surely I will try.

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 3 lety +1

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

  • @prakad97
    @prakad97 Před 4 lety +1

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

  • @VilliSopuli
    @VilliSopuli Před 3 lety +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.

  • @ChocolateMilkCultLeader
    @ChocolateMilkCultLeader Před 4 lety +5

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

  • @jaatharsh
    @jaatharsh Před 6 měsíci

    awesome well explained, thanks buddy

  • @raviashwin1157
    @raviashwin1157 Před 4 lety

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

  • @faraz7409
    @faraz7409 Před 4 lety

    my man! thanks for the vid very helpful!

  • @somasishsahoo
    @somasishsahoo Před 4 lety +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

  • @kumarc4853
    @kumarc4853 Před 3 lety

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

  • @TheRaviraaja
    @TheRaviraaja Před 3 lety

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

  • @aliara1568
    @aliara1568 Před 3 lety

    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 Před 3 lety +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;
    }

  • @divyanshukr
    @divyanshukr Před 4 lety +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 Před 4 lety +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;
      }

  • @raviapiit
    @raviapiit Před 3 lety

    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. :)

  • @renetchi
    @renetchi Před 3 lety

    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

  • @tusharmarda295
    @tusharmarda295 Před 4 lety +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  Před 4 lety

      Nice!

    • @jkrw3540
      @jkrw3540 Před 4 lety

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

  • @JSDev776
    @JSDev776 Před 3 lety

    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?

  • @chrisy.703
    @chrisy.703 Před 2 lety

    excellent greedy method

  • @AshokBathini
    @AshokBathini Před 4 lety +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 Před 3 lety

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

    • @lazzuuu21
      @lazzuuu21 Před rokem

      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(?)

  • @dipteshsil9299
    @dipteshsil9299 Před 4 lety +2

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

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 4 lety

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

    • @dipteshsil9299
      @dipteshsil9299 Před 4 lety

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

    • @jasminegeorge1149
      @jasminegeorge1149 Před 4 lety

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

    • @ozgurgonen9061
      @ozgurgonen9061 Před 3 lety

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

  • @surendra9935
    @surendra9935 Před 4 lety +2

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

  • @godismygeneral
    @godismygeneral Před 4 lety

    Hey Kevin what is the runtime of this algo?

    • @utalmighty
      @utalmighty Před 3 lety +1

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

  • @shriharikulkarni3986
    @shriharikulkarni3986 Před 2 lety

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

  • @vaishali874
    @vaishali874 Před 4 lety

    can we use a subsequence more than once?

  • @zn4798
    @zn4798 Před 3 lety +1

    Brute force TLE!

  • @surepasu
    @surepasu Před 3 lety

    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 Před 3 lety

      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".

  • @abhinavgupta750
    @abhinavgupta750 Před 3 lety

    Can source have character duplication?

  • @sureshchaudhari4465
    @sureshchaudhari4465 Před 2 lety

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

  • @gnanyreddy3030
    @gnanyreddy3030 Před 2 lety

    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

  • @zhakaske5671
    @zhakaske5671 Před 3 lety +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 Před 3 lety +2

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

  • @charan775
    @charan775 Před 4 lety +1

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

  • @scnullois
    @scnullois Před 4 lety

    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.

  • @sharkk2979
    @sharkk2979 Před 3 lety

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

  • @harsha2s2udupa
    @harsha2s2udupa Před 4 lety +3

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

    • @ShaliniNegi24
      @ShaliniNegi24 Před 3 lety

      I was also thinking of this test case :/

    • @ShaliniNegi24
      @ShaliniNegi24 Před 3 lety

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

    • @-harshayadav
      @-harshayadav Před 3 lety

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

  • @rahulshrivastava3040
    @rahulshrivastava3040 Před 4 lety

    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.

  • @vk1618
    @vk1618 Před 4 lety

    Check alternate soln

  • @krishnamohansharma8859

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

  • @pratikchowdhury9210
    @pratikchowdhury9210 Před 4 lety

    Lol that 1 dislike wonder why