Maximum Score Words Formed By Letters - Leetcode 1255 - Python

Поділитися
Вставка
  • Опубліковано 12 вер 2024

КОМЕНТАРІ • 34

  • @BilalShaikh-tn9wu
    @BilalShaikh-tn9wu 3 місяці тому +31

    this one was 10x easier than yesterdays & its a hard?? crazy

    • @pastori2672
      @pastori2672 3 місяці тому +4

      tf do you mean yesterday was a simple backtracking problem sure the most optimal solution is hard to come up with but a simple backtracking solution passes

    • @EduarteBDO
      @EduarteBDO 3 місяці тому

      @@pastori2672 yesterday was not that simple, if you miss to account duplicate you would end up in a bunch of edge cases without knowing why. that's what happened with me.

    • @erminiottone
      @erminiottone 3 місяці тому

      🤯

  • @csam11100
    @csam11100 3 місяці тому +3

    Is the space complexity should be O(n +26)?
    n is for recursive stack and 26 for the letter_cnt.
    I think we can ignore the space created in the helper function like word_cnt (O(26) if considered)
    please correct me if I am wrong.
    Thanks

    • @gameacc6079
      @gameacc6079 3 місяці тому

      W is from Counter(W), the length of the longest word. It is used in the computation of word_cnt

  • @hamirmahal
    @hamirmahal 3 місяці тому

    I really liked the rationale for not pre-computing each word's score. Thanks for including it.

  • @MP-ny3ep
    @MP-ny3ep 3 місяці тому +1

    Beautiful explanation. Thank you

  • @sophiophile
    @sophiophile 3 місяці тому

    I think python lets you just subtract the counters `if can_form_word()`, no need to make the loop explicit.

  • @DNKF
    @DNKF 3 місяці тому +2

    Could you try the 332 Reconstruct Itinerary using Hierholzer's algorithm please? LC new test case makes the previous solution failed.

    • @n2ck
      @n2ck 3 місяці тому +1

      his code still works but in the dfs body you just add a failedneighbors set so you can skip neighbors that you know wont work.
      class Solution:
      def findItinerary(self, tickets: List[List[str]]) -> List[str]:
      tickets.sort()
      # build graph
      graph = defaultdict(list) # for now Str --> [Listof Str]
      for src, dst in tickets:
      graph[src].append(dst)

      def dfs(currAirport, currAns):
      if len(currAns) == len(tickets) + 1:
      return currAns

      if currAirport not in graph:
      return None

      temp = graph[currAirport].copy()
      failedneighbors = set()
      for i, nei in enumerate(temp):
      if nei in failedneighbors:
      continue
      graph[currAirport].pop(i)
      currAns.append(nei)
      res = dfs(nei, currAns)
      if res:
      return res
      failedneighbors.add(nei)

      graph[currAirport].insert(i, nei)
      currAns.pop()

      return None

      return dfs('JFK', ['JFK'])

  • @ywsoliman
    @ywsoliman 3 місяці тому

    Can't we use memoization for better time complexity?

  • @chien-yuyeh9386
    @chien-yuyeh9386 3 місяці тому +2

    Thanks!

  • @corrogist692
    @corrogist692 3 місяці тому

    I did not add back the letters, but created a copy of the counter (since its of length 26 anyway) before the subtractions, then pass the new counter to the backtracking function as a para. Would this be slightly more efficient?

  • @varunpalsingh3822
    @varunpalsingh3822 3 місяці тому +1

    I didn't understand the space complexity part,
    firstly, len(word_cnt) will never exceed the 26, we doesn't include letter_cnt into the space complexity, then we are considering the word_cnt,
    and secondly, we were given words so why we are considering it to include in space complexity ??

    • @NeetCodeIO
      @NeetCodeIO  3 місяці тому

      Length of words determines size of call stack.

    • @varunpalsingh3822
      @varunpalsingh3822 3 місяці тому

      @@NeetCodeIO ya now got it 👍🏻

  • @hithambasheir3283
    @hithambasheir3283 3 місяці тому

    I tried to be smart by adding a memo for if a word is valid or not, not knowing that this will miss for other cases, took me so long to figure it out 🤦‍♂

  • @toterG0tt
    @toterG0tt 3 місяці тому

    Thank you!

  • @rostislav_engineer
    @rostislav_engineer 3 місяці тому

    thanks for this video!

  • @joydeeprony89
    @joydeeprony89 3 місяці тому

    this is the first time I did not understand your explanation in the first go.

  • @pastori2672
    @pastori2672 3 місяці тому +1

    so happy to solve this on my own 🙂

  • @albedo9617
    @albedo9617 3 місяці тому

    Might be a basic question but why are we increasing the letter_cnt on line 28 again. We've already made the recursive calls for both the cases on line 22 and 26 already. So we'll be sending the reduced count to 26 anyway and increasing the count shouldn't matter? I'm coding this in java tho

    • @AMakYu
      @AMakYu 3 місяці тому +2

      As you are moving back up the recursive stack, you must ensure that the letter count is consistent with where you are in the decision tree. If you only decrement, then when you go back up the stack and go down a different branch in the decision tree, the letter count will not be consistent anymore and it may think the following words are invalid because of it. Resetting the state as you go back up the stack is important and is part of the "backtracking".

    • @albedo9617
      @albedo9617 3 місяці тому

      @@AMakYu can you check why this one works even though I'm not increasing the count again?
      class Solution {
      public int maxScoreWords(String[] words, char[] letters, int[] score) {
      HashMap charCounter = new HashMap();
      for(int i = 0; i < letters.length;i ++){
      charCounter.put(letters[i], charCounter.getOrDefault(letters[i],0) + 1);
      }
      return solver(words,score, 0, charCounter);
      }
      public int solver(String[] words, int[] score, int index, HashMap counter){
      if(index == words.length){
      return 0;
      }
      int s1 = solver(words,score,index+1,new HashMap(counter));
      int s2 = 0;
      int tempScore = 0;
      if(canWordBeFormed(words[index], counter)){
      System.out.println("Word formed");
      tempScore = getWordScore(words[index],score);
      System.out.println(tempScore);
      s2 = tempScore + solver(words, score, index+1,counter);
      }
      return Math.max(s1,s2);
      }
      public boolean canWordBeFormed(String word, HashMap counter){
      for(int i = 0 ; i < word.length(); i++){
      if(counter.get(word.charAt(i)) == null || counter.get(word.charAt(i))

  • @Perry-tf2pr
    @Perry-tf2pr 3 місяці тому

    Can we first include word[w] then add score and cnt last exclude word[x] in backtrack method?

    • @Munchen888
      @Munchen888 3 місяці тому

      I think if you want you can initially skip and then include if every single char in hashmap. But I doubt about base case 🧐 If I’m wrong correct me please. If we are at last word thus we should to count total score of word. Count using our score map and return … 🙂‍↔️

    • @Perry-tf2pr
      @Perry-tf2pr 3 місяці тому

      @@Munchen888
      If valid then can be but invalid I initially set 0 . yea passed . If didn’t initiall set,it will raise exception

  • @HolaAmigohehe
    @HolaAmigohehe 3 місяці тому

    Cant we memoize this?

  • @galkk3
    @galkk3 3 місяці тому

    I think I did very similar but my runtime is about 1000 ms, how is it possible?

  • @ajinzrathod
    @ajinzrathod 3 місяці тому

    TIP: If you first backtrack the excluded ones and then backtrack the included ones, you won't need to adjust the count again.

  • @karlebh
    @karlebh 3 місяці тому

    couple extra dss 😁

  • @venky3639
    @venky3639 3 місяці тому

    Damn i couldn't understand that one

  • @krateskim4169
    @krateskim4169 3 місяці тому

    Thank you so much