Number of Good Leaf Nodes Pairs - Leetcode 1530 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 ม.ค. 2025

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

  • @NeetCodeIO
    @NeetCodeIO  5 หลายเดือนก่อน +26

    btw I finally launched Python for coding interviews 🚀🚀 should i do Java for coding interviews next?
    neetcode.io

    • @jonaskhanwald566
      @jonaskhanwald566 5 หลายเดือนก่อน

      Definitely yes

    • @DNKF
      @DNKF 5 หลายเดือนก่อน +1

      Please share anything you think it may help us to understand how to play the interview games!
      I was very sacry about interviews until I started watching yours. So I believe everything you shared did help!

    • @arihantsinghrana2173
      @arihantsinghrana2173 5 หลายเดือนก่อน

      Is C++ also required by the industries ? or is it just helpful for competitive programming?

    • @takeuchi5760
      @takeuchi5760 5 หลายเดือนก่อน

      ​​@@arihantsinghrana2173 there is plenty of work in cpp ofc, but you have to be very good at it if you want a job for it, dsa c++ barely scratches the surface of how skilled one needs to be with cpp to get a job.

    • @fraserdab
      @fraserdab 5 หลายเดือนก่อน

      cpp

  • @JamesBond-mq7pd
    @JamesBond-mq7pd 5 หลายเดือนก่อน +4

    Even first solution is super clever. Incredible. i tried to crack this problem for 2 hours. and made very complex and slow solution

  • @fancypants6062
    @fancypants6062 5 หลายเดือนก่อน +8

    Thanks for including the BFS version also. I think it really enhances the learning & understanding.

  • @MadpolygonDEV
    @MadpolygonDEV 5 หลายเดือนก่อน +6

    omg, my initial intuition had this solution but i disregarded it and thought, no way we combine lists and compare distances every level. Theres probably a smarter solution :/

  • @freecourseplatformenglish2829
    @freecourseplatformenglish2829 5 หลายเดือนก่อน

    I am really happy that I almost solved it on my own with optimized solution. There was a little bug but your video helped me fix it.

  • @pritz9
    @pritz9 5 หลายเดือนก่อน +3

    Add this line :-
    if d1 >= distance :
    continue
    before the for loop of d2. This will improve the time complexity significantly. My submission beats % went from 37 to 95 by this single change.

    • @rahulsbhatt
      @rahulsbhatt 5 หลายเดือนก่อน +1

      You are right! This one is actually pretty good! Helped the solution reach 90ms from 124 ms.

    • @pritz9
      @pritz9 5 หลายเดือนก่อน

      @@rahulsbhatt yeah, we are skipping useless iterations in this case.

  • @anandsrikumar007
    @anandsrikumar007 5 หลายเดือนก่อน

    I submitted 10+ times, at last my submission was accepted. I discovered a technique with iteration. I will calculate the distances while doing dfs itself.

  • @zhuoxiao6697
    @zhuoxiao6697 5 หลายเดือนก่อน +2

    Best professor

  • @arihantsinghrana2173
    @arihantsinghrana2173 5 หลายเดือนก่อน

    Waking up in the morning to your video is one of the best things I do the whole day!! Thanks for your Daily uploads and keep up the great work!!

  • @王瀚君-c3j
    @王瀚君-c3j 5 หลายเดือนก่อน

    Thank you bro. You save my day.

  • @business_central
    @business_central 5 หลายเดือนก่อน

    Thanks for including the last solution, can someone tell me what was the time and space complexity of the last one?

  • @abdallaahmed1325
    @abdallaahmed1325 5 หลายเดือนก่อน

    Can u make a playlist and explain the Data structure and algorithms?
    Because there are not much good resources out there

  • @chien-yuyeh9386
    @chien-yuyeh9386 5 หลายเดือนก่อน +4

    First!!🎉

    • @SachinRajput
      @SachinRajput 5 หลายเดือนก่อน +1

      And the award goes to....

  • @navneetkharb5888
    @navneetkharb5888 5 หลายเดือนก่อน

    Great explaination as always

  • @ZaneMouakket
    @ZaneMouakket 5 หลายเดือนก่อน

    I originally made the bfs graph solution with the optimization you made at 19:50. After including that optimization the time complexity would be O(n(2^d)), right?
    This would be better than O(n^2).

    • @ZaneMouakket
      @ZaneMouakket 5 หลายเดือนก่อน

      Or it's O(n*max(n,2^d))

  • @SmoothCode
    @SmoothCode 2 หลายเดือนก่อน

    Why do we want to do [d+1 for d in all_dist] for? Is that not already handled in the base case?

  • @prakhar_kesar
    @prakhar_kesar 5 หลายเดือนก่อน

    Thanks man!!

  • @harikrishnasadhu9581
    @harikrishnasadhu9581 5 หลายเดือนก่อน

    A Biggg Yesss for java

  • @GeetainSaar
    @GeetainSaar 5 หลายเดือนก่อน

    thaks khushi :)) you are so genius. ya thats me

  • @prinksters129
    @prinksters129 5 หลายเดือนก่อน

    can you please make a video on optimal account balancing i am so confused!!!!

  • @IK-xk7ex
    @IK-xk7ex 5 หลายเดือนก่อน

    I think graph solution is not appropriate for that problem, because it doesn't state that node values are unique. Thank you for the solution!

    • @Pegasus02Kr
      @Pegasus02Kr 5 หลายเดือนก่อน

      Honestly I think I would reject this graph solution if I were an interviewer. I don't think building a whole new graph from a tree is a proper solution here.

    • @m.kamalali
      @m.kamalali 5 หลายเดือนก่อน

      It does work with repeated nodes bcs python gives diffrent hashes for diffrent objects even if they have the same structure

  • @PhanNghia177
    @PhanNghia177 5 หลายเดือนก่อน

    I'm sorry but the hash_map solution seem weird, isn't we just need to remove all the value d + 1 that surpass distance ?
    Anyway, about all_dist[d + 1] = left_dict[ d + 1] feel so wrong,
    left_dict[d + 1] should be 0 right ?

  • @sauravsingh4497
    @sauravsingh4497 5 หลายเดือนก่อน

    Can anyone tell me how does one come up with a recursive solution for a problem like this

    • @SarweshParsewar
      @SarweshParsewar 5 หลายเดือนก่อน

      its all about practise and we need to solve a certain amount of problems to get that level of intuition its just a matter of time and practise you could come up with such unique approaches. Try solving neetcode 150 problems it really helped me to build a intuition for the new problems.

  • @ArunRampure
    @ArunRampure 5 หลายเดือนก่อน

    What tool do you use to explain the solution?

  • @nikhil199029
    @nikhil199029 5 หลายเดือนก่อน +1

    It's not what it looks like
    -neetcode 2024

  • @Itsme-hr4hw
    @Itsme-hr4hw 5 หลายเดือนก่อน

    i don't know why we require to return list, i mean we can customize the function and only return number of leaf nodes which have depth less than equal to distance and then for multiply left and right and then add to the totalPairs

    • @rahulsbhatt
      @rahulsbhatt 5 หลายเดือนก่อน

      I was thinking the same and then asked ChatGPT, which helped with understanding that just returning the leaf nodes isn't correct because we need the distance between the leaf nodes and not the count.
      Following is what chatGPT gave:
      Let's take an example:
      1
      / \
      2 3
      / \ \
      4 5 6
      Leaf Nodes and Distances
      Leaf nodes: 4, 5, 6
      Distances from the root:
      Distance from 1 to 4: 2
      Distance from 1 to 5: 2
      Distance from 1 to 6: 2
      Given Distance = 3
      Now, let's try counting pairs of leaf nodes such that the distance between them is less than or equal to 3.
      Direct Multiplication of Counts
      If we only count the number of leaf nodes in each subtree and multiply them directly:
      Leaf nodes in the left subtree (nodes 2, 4, 5): 2 (nodes 4 and 5)
      Leaf nodes in the right subtree (nodes 3, 6): 1 (node 6)
      Multiplying these counts:
      Pairs=2×1=2
      However, this approach fails to consider the actual distances between leaf nodes. The correct count should be based on valid distances between the pairs.
      Correct Pair Counting with Distances
      Using the distances:
      Distances from leaf nodes in the left subtree to the root (1): [2, 2]
      Distances from leaf nodes in the right subtree to the root (1): [2]
      Now we need to check the pairs:
      Pair (4, 6): Distance = 2 + 2 = 4 (not a valid pair since 4 > 3)
      Pair (5, 6): Distance = 2 + 2 = 4 (not a valid pair since 4 > 3)
      None of these pairs are valid according to the given distance constraint (3).
      Correct Solution
      By considering actual distances, the number of valid pairs is 0, not 2.

  • @rahulsbhatt
    @rahulsbhatt 5 หลายเดือนก่อน

    I didn't understand O(N * D^2) optimization

  • @susdoge3767
    @susdoge3767 5 หลายเดือนก่อน

    alright my trees and recursion is a mess

  • @aadil4236
    @aadil4236 5 หลายเดือนก่อน

    I solved it with 10*n^2 time complexity and it gave me time limit exceed but it gets accepted for n^3 why? Can somebody tell me if I am right about my time and space complexity? here's the code:
    /**
    * Definition for a binary tree node.
    * function TreeNode(val, left, right) {
    * this.val = (val===undefined ? 0 : val)
    * this.left = (left===undefined ? null : left)
    * this.right = (right===undefined ? null : right)
    * }
    */
    /**
    * @param {TreeNode} root
    * @param {number} distance
    * @return {number}
    */
    var countPairs = function(root, distance) {
    // create parent binding
    // get all the leaf node in pre-order-traversal order.
    // try to get each node to the right of it and see if it's a good node.
    // a bfs helper function which takes src and target and gives as all the possible good nodes.
    const bindTree = (root) => {
    const dfs = (node, pre) => {
    if(!node) return;
    node.parent = pre;
    dfs(node.left, node);
    dfs(node.right, node);
    }
    dfs(root, null);
    }
    const getLeafNodes = (root) => {
    const leafNodes = [];
    const dfs = (node) => {
    if(!node.left && !node.right) {
    leafNodes.push(node);
    return;
    }
    node.left && dfs(node.left);
    node.right && dfs(node.right);
    }
    dfs(root);
    return leafNodes;
    }
    const shortestPath = (src, target, limit) => {
    const bfs = (node) => {
    const q = new Queue();
    const visited = new Set();
    q.enqueue([src, 0]);
    while(!q.isEmpty()) {
    const [node, currDistance] = q.dequeue();
    visited.add(node);

    if(currDistance > limit) continue;
    if(node === target) return true;
    // add neighbor nodes.
    if(node.left && !visited.has(node.left)) {
    q.enqueue([node.left, currDistance+1]);
    }
    if(node.right && !visited.has(node.right)) {
    q.enqueue([node.right, currDistance+1]);
    }
    if(node.parent && !visited.has(node.parent)) {
    q.enqueue([node.parent, currDistance+1]);
    }
    }
    return false;
    }
    if(bfs(src)) return true;
    return false;
    }
    bindTree(root);
    const leafNodes = getLeafNodes(root);
    let goodPairs = 0;
    for(let i = 0; i < leafNodes.length; i++) {
    const srcNode = leafNodes[i];
    for(let j = i+1; j < leafNodes.length; j++) {
    const targetNode = leafNodes[j];
    if(shortestPath(srcNode, targetNode, distance)) {
    goodPairs++;
    }
    }
    }
    return goodPairs;

    };

  • @Thorffin55
    @Thorffin55 5 หลายเดือนก่อน

    Day 2 of asking #987 explanation

  • @АлекСневар
    @АлекСневар 5 หลายเดือนก่อน +1

    If you wanna declare a class variable, you don't need to use self. So your original code would work, if you deleted self from the topmost declaration of pairs variable

  • @crazyy_av
    @crazyy_av 5 หลายเดือนก่อน +1

    "leaf nodeS pairS" 🤣🤣🤣

  • @RK-cd
    @RK-cd 5 หลายเดือนก่อน

    shame shame shame!!!! NO JAVA However course corrected so all good