Car Fleet - Leetcode 853 - Python

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

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

  • @Grawlix99
    @Grawlix99 2 ปีที่แล้ว +107

    As others mentioned, you don't need a stack. Simple code:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    pairs = [(position[i], speed[i]) for i in range(len(position))]
    fleets = curtime = 0 # a car's position is always < than target at the start, so it's fine to start curtime at 0 (no fleet will be at target at time 0)
    for dist, speed in sorted(pairs, reverse=True):
    destination_time = (target - dist)/speed
    if curtime < destination_time:
    fleets += 1
    curtime = destination_time
    return fleets

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

      I did the same exact way, but wasn’t passing all the tests using python (not python3). Then I tried on python3 after seeing yours, and both of them work! do you know why it doesn’t;t work on python tho?

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

      @@albertd7658 no idea, unfortunately... Perhaps some syntax change?

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

      @@Grawlix99 yea I guess so... But thanks anyway!

    • @AlexAlex-bb8db
      @AlexAlex-bb8db ปีที่แล้ว +6

      @@albertd7658
      FYI: It's a difference in how division works in Python2 and Python3.
      Here is the correct code for Python 2:
      class Solution(object):
      def carFleet(self, target, position, speed):
      pairs = [(position[i], speed[i]) for i in range(len(position))]
      fleets = curtime = 0
      for dist, speed in sorted(pairs, reverse=True):
      destination_time = float((target - dist))/speed
      if curtime < destination_time:
      fleets += 1
      curtime = destination_time
      return fleets
      Pay attention to the difference how we calculate the destination_time. I hope it helps you!

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

      @@AlexAlex-bb8db thanks a lot for the explanation!

  • @dk20can86
    @dk20can86 2 ปีที่แล้ว +82

    For most of these stack questions i've been finding that a simple counter variable is my intuition and is more space efficient than a stack

    • @Trizzi2931
      @Trizzi2931 2 ปีที่แล้ว +12

      Like in this question all you need to do is take a counter and increment it whenever you find a higher time take to reach the target

    • @stardrake691
      @stardrake691 ปีที่แล้ว +10

      same, I don't like when solutions use stacks just for the sake of using a stack.

    • @Tyler-jd3ex
      @Tyler-jd3ex ปีที่แล้ว +4

      I just did that instead. It was a little more difficult just to arrange things in a way as to avoid having too many if statements but I managed.
      counter = 0
      cars = [[p, s] for p, s in zip(position, speed)]
      last = -1
      for p, s in sorted(cars)[::-1]:
      cur = (target - p) / s
      if last != -1 and cur

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

      I just never get an intuition naturally to use a stack. My only weaknesses are stacks and heaps. Others I could still manage.😢

    • @ta32dev
      @ta32dev 9 หลายเดือนก่อน +1

      @@stardrake691 His approach indexes the second element of a stack - which wont work in most languages that implement a stack idiomatically and doesn't allow developers to index a stack. If you need indexing to access any element of the stack why are you using a stack?

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

    This medium problem feels like hard one.

  • @AmanSingh-ou6tq
    @AmanSingh-ou6tq 2 ปีที่แล้ว +79

    Very well explained. Like others also explained, we don't really need a stack here. I spent a lot of time trying to think of a linear approach as this was listed in the stack category. Regardless, you are doing very good work man. Thanks again.

    • @ta32dev
      @ta32dev 9 หลายเดือนก่อน +2

      Yeah I don't see why its a "stack problem" especially since most languages don't allow any access to the second element of the stack. Since you should only referencing or using the top of the stack.

  • @OrkhanAlizade
    @OrkhanAlizade 2 ปีที่แล้ว +51

    I rarely leave any comment but I could not resist. The explanation was on top! You chewed the problem so well!

  • @symbol767
    @symbol767 2 ปีที่แล้ว +160

    I hate problems like this, honestly it just makes me feel beyond dumb. This was a difficult one, I hate how interviewers ask this stuff

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

      It is just a matter of solving a lot of problems.

    • @ssuriset
      @ssuriset 4 หลายเดือนก่อน +3

      I love physics more than computer science.

    • @princeofexcess
      @princeofexcess 4 หลายเดือนก่อน +1

      @@ssuriset are you just as good at both?

    • @ssuriset
      @ssuriset 4 หลายเดือนก่อน

      @@symbol767 Physics, I am really really good, but computer science…. not sure

    • @princeofexcess
      @princeofexcess 4 หลายเดือนก่อน +1

      @saisurisetti6278 we prefer what we are good at. People who hate math are usually terrible at it. Once they get good at it, they don't hate it anymore.

  • @HrishikeshDeshpande
    @HrishikeshDeshpande 3 ปีที่แล้ว +98

    No need to use stack, just use a variable to keep track of slowest arrival time and increase the counter if we find new slower.

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

      that's what i was thking, regardless i don't think you have to be spot on for most of these questions. It's a negligible change in efficiency .

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

      yeah just checked it 92 ms diff on average not too big of a deal from better than 89% to better than 99.7%

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

      Sometimes interviewers don't like extra space 😅

    • @shivamgarg4201
      @shivamgarg4201 3 ปีที่แล้ว +15

      We need extra space for pairs array anyways so its not like we are reducing from O(n) to O(1)

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 2 ปีที่แล้ว +1

      This approach would work with right to left only, correct ?
      # Change position array, in place, to avoid an extra O(n) array
      for index, s in enumerate(speed):
      position[index] = (position[index], s)
      position.sort()
      if len(position) == 1:
      return 1
      slowest_car = -1
      car_fleet = 0
      for p, s in position[::-1]:
      if (target - p)/s > slowest_car:
      slowest_car = (target-p)/s
      car_fleet += 1
      return car_fleet

  • @brianevans4975
    @brianevans4975 2 ปีที่แล้ว +609

    Did anyone else find this problem pretty hard?

    • @symbol767
      @symbol767 2 ปีที่แล้ว +92

      This problem sucks honestly

    • @mk-19memelauncher65
      @mk-19memelauncher65 2 ปีที่แล้ว +27

      Especially when youre not using python so sorting array of tuples is a pain

    • @tanaykamath1415
      @tanaykamath1415 2 ปีที่แล้ว +18

      @@mk-19memelauncher65 especially while using Java😭😭

    • @leeroymlg4692
      @leeroymlg4692 ปีที่แล้ว +66

      finding it hard just to understand what the problem is asking!

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

      No, it was fine. Pretty easy actually if you're not a brainlet.

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

    I don't think I ever would've come-up with this solution on my own. Excited to take my DS & A class this Fall to better understand these concepts. Thanks so much for the explanation!

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

    if you're failing the test cases make sure you're using python3 and not python. python 3 allows for true division, meaning (target - position) / speed will be a floating point number. Before python3, you have to manually convert one of the values to a float, otherwise it will round down to the nearest integer.

    • @kiss_my_axe
      @kiss_my_axe 11 หลายเดือนก่อน

      Bingo

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

    I'm going through the neetcode roadmap. I could not figure out why a stack was used, until this video. thank you Neetcode thank you

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

    You can do list(zip(position, speed)) to convert the zip iterator to a list, which is a bit shorter. Although you don't really need it because you can call sorted() directly on the zip iterator.

  • @codeitaviral3
    @codeitaviral3 8 วันที่ผ่านมา +1

    the c++ code for the above:
    class Solution {
    public:
    static bool cmp(paira,pairb)
    {
    return (a.first >b.first);
    }
    int carFleet(int target, vector& position, vector& speed)
    {
    int n = position.size();
    vector ps;
    stack st;
    for (int i = 0; i < n; i++)
    {
    ps.push_back({position[i], speed[i]});
    }
    sort(ps.begin(), ps.end(),cmp);
    for(int i=0;i st.top())
    {
    st.push(time_to_reach_des);
    }
    }
    return st.size();
    }
    };

  • @vineethsai1575
    @vineethsai1575 2 ปีที่แล้ว +8

    I used time as a parameter to determine if one car can catch another.
    # POSITION, SPEED, TIME
    # [(10, 2, 1.0), (8, 4, 1.0), (5, 1, 7.0), (3, 3, 3.0), (0, 1, 12.0)]
    Now use this time parameter, if previous car has time

  • @yt-sh
    @yt-sh 3 ปีที่แล้ว +22

    the understanding portion of this video is well made!

  • @gregoryvan9474
    @gregoryvan9474 2 ปีที่แล้ว +12

    If you are using a stack, you can actually go from left to right (smallest position to biggest position) using a while loop to pop values out, see my code below. However, as others stated in the comments, you can just use a counter variable if going from right to left and avoid using a stack at all.
    def carFleet(target, position, speed):
    pair = [[p, s] for p,s in zip(position, speed)]
    stack = []
    for p, s in sorted(pair):
    eta = (target-p)/s
    if not stack:
    stack.append(eta)
    else:
    while stack and eta >= stack[-1]:
    stack.pop()
    print(stack)
    stack.append(eta)
    return len(stack)

    • @davidkang833
      @davidkang833 2 ปีที่แล้ว +6

      Here's a solution without using a stack:
      def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
      combined = sorted(zip(position, speed))
      prev_time = 0
      num_fleets = 0
      for pos, speed in combined[: : -1]:
      curr_time = (target - pos) / speed
      if curr_time > prev_time:
      num_fleets += 1
      prev_time = curr_time
      return num_fleets

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

      @@davidkang833 you might fail on floating point operations. Its better to compare times multiplied by distance:
      ...
      if curr_distance * prev_speed > prev_distance * curr_speed:
      ...

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

      @@davidkang833 Very nice, you're hired ✅

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

    I loved the fact that you demonstrated the process and then jumped on the actual solution! Kudos doing a great job!!

  • @kartikhegde533
    @kartikhegde533 7 หลายเดือนก่อน

    Was able to come up with this solution relatively easily using priority queue. I did submit 4 wrong answers before getting the right logic. Probably because I am solving the neetcode 150 stack series, it became relatively easier. I often find these problems to be solvable by IMAGINING HOW A PERSON WOULD SOLVE THIS MANUALLY.

  • @tejas8211
    @tejas8211 3 หลายเดือนก่อน

    I really appreciate the fast that it's a physics problem. That's exactly how these problems should be - based on real world problem not these simple put the object in array kinda.

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

    Great Video! Also one improvement. We don't need stack. If two cars collide then we can simply change the position and speed of current car to be same as the next car. Below is the C++ code:
    class Solution {
    public:
    class Cmp {
    public:
    bool operator()(const vector &v1, const vector &v2) const {
    return v1[0] < v2[0];
    }
    };
    int carFleet(int target, vector& position, vector& speed) {
    vector cars;
    for(int i = 0; i < position.size(); i++) {
    cars.push_back({position[i], speed[i]});
    }
    sort(cars.begin(), cars.end(), Cmp());
    int n = cars.size();
    int fleetsCount = 1;
    for(int i = n-2; i >= 0; i--) {
    double speedNext = cars[i+1][1], speedCurr = cars[i][1];
    double posNext = cars[i+1][0], posCurr = cars[i][0];
    // time it will take to reach the target
    double timeNext = (double) (target - posNext) / speedNext;
    double timeCurr = (double) (target - posCurr) / speedCurr;
    // if speedNext > speedCurr then it will never form a fleet
    // if timeCurr

  • @akshaygoel2184
    @akshaygoel2184 2 ปีที่แล้ว +10

    Really nice explanation and video!
    Just a Python comment I think using sorted( ..., reverse=True) or reversed( (sorted(...)) is more optimal here. This prevents you from duplicating memory.

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

      I did not understand why we have to sort it

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

      @@shakthivelcr7 so you get the cars on track according to their positions first. Given data is not sorted if you see it. Consider cars with positions 20, 10, 5. So if speed of car 5 is greater than both other cars 10, 20. 5 will only collide with 10 and then make a fleet but will not collide to 20. Its just real world mapping, so sorting scene is here.We need to put cars as per the position so that fleet can only be made with adjacent objects. Hope m not confusing you more
      [20,5, 10] --> after sorting [ 5 --> 10 --> 20], see 5 can make fleet with 10 not 20, similarly 10 can make fleet with 20. So when we sort and traverse on reversed list, we can easily create fleets.

  • @ritiksaxenaofficial
    @ritiksaxenaofficial 9 หลายเดือนก่อน

    Good explanation, we can also calculate time taken by current car and last car in stack and if current car is taking more time then append current car in the stack. Time Complexity for me was 718ms.
    Note: append last element in pair in the stack first and then check for further elements via loop.

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

    this is the best video on this channel, love how you broke it down to the end, top tier content!

  • @XxM1G3xX
    @XxM1G3xX 9 หลายเดือนก่อน

    In case anyone wants to know how would the answer look using a hashmap here it is:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    hm = {position[i]: speed[i] for i in range(len(position))}
    stack = []
    for pos in sorted(hm.keys(), reverse = True):
    time = (target - pos) / hm[pos]
    if not stack or time > stack[-1]:
    stack.append(time)
    return len(stack)

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

    I will be a loyal neetcode user for the rest of my swe career. Thank you, Sir!

  • @ocoocososococosooooosoococoso
    @ocoocososococosooooosoococoso 2 ปีที่แล้ว +3

    One of the best explanations from this channel!

    • @PIYUSH-lz1zq
      @PIYUSH-lz1zq 2 ปีที่แล้ว

      why we are not counting whenever stack[-1]

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

    Thanks for the video, based on your explanation, I think we don't need stack DS at all for this problem. Here is my solution with C++ which works fine without stack:
    class Solution {
    public:
    int carFleet(int target, vector& position, vector& speed) {
    vector availCarFleet;
    for (int i=0; i

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

    I did this problem in a very similar way but on forward order using a decreasing monotonic stack.
    n = len(position)
    stack = []
    cars = sorted(
    [(position[i], speed[i]) for i in range(n)]
    )
    for pos, sped in cars:
    units_to_reach = (target-pos)/sped

    while stack and stack[-1]

    • @elab4d140
      @elab4d140 3 หลายเดือนก่อน

      yes, this was clear after solving daily temperatures problem

  • @bltgz
    @bltgz 8 หลายเดือนก่อน +1

    Here is a solution without reversing
    for p,s in sorted(pair):
    arrival = (target-p)/s
    while stack:
    if stack[-1]

  • @EranM
    @EranM 7 หลายเดือนก่อน

    you could substract the target from the positions to get the graph start from 0, 0 :>

  • @VarunMittal-viralmutant
    @VarunMittal-viralmutant 2 ปีที่แล้ว +3

    Left to right works too:
    pos_speed = sorted(zip(position, speed))
    car_fleet = []
    for p, s in pos_speed:
    if not car_fleet:
    car_fleet.append((target - p) / s)
    continue
    # Next car is slower speed than previous one
    while car_fleet and (target - p)/s >= car_fleet[-1]:
    car_fleet.pop(-1)
    car_fleet.append((target - p)/s)
    return len(car_fleet)

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

      Won't the reverse order be a tad bit faster because of not having the while loop (for large inputs)?

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 2 ปีที่แล้ว

      @@arkamukherjee457 It may impact the number of comparison like >= or

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

      @@VarunMittal-viralmutant but you dont really need a stack

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 2 ปีที่แล้ว

      @@minciNashu If you are working from left to right, then you do. From right to left, it is not

  • @tempestofsouls5693
    @tempestofsouls5693 2 ปีที่แล้ว +11

    The solution makes sense in hindsight. How do we come up with this on the spot though? The problem seems pretty ad-hoc and no obvious signs as to what data structure or algorithm can be used

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

    I really need to draw more diagrams, I was sure time played a role, but I couldn't figure out how until i saw this. great video and explanation ❤

  • @Bagunka
    @Bagunka 7 หลายเดือนก่อน +1

    Wow that linear equation visualization was just 👌👌

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

    You don't even need to sort the array, you can just use the initial car positions as as the index to an array that maps to how long it takes each car to arrive at the destination. making it O(n). This problem would definitely fit better on the arrays and hashing section.

  • @zaffa12
    @zaffa12 8 หลายเดือนก่อน +3

    This one made me cry in my sleep, no way this is medium

  • @michaelbrock1414
    @michaelbrock1414 7 หลายเดือนก่อน

    Here's my linear O(target) time and space complexity solution in JS. No stacks necessary. FWIW I found the trick behind this solution really similar to that of Leetcode 347.
    var carFleet = function(target, position, speed) {
    const arrivalTimesByPosition = new Array(target).fill(-1);
    for (let i = 0; i < position.length; i++) {
    const distanceToTravel = target - position[i];
    const arrivalTime = distanceToTravel / speed[i];
    arrivalTimesByPosition[position[i]] = arrivalTime;
    }
    // arrivalTimesByPosition will be an array sorted by starting
    // positions. It'll likely have dummy slots filled with -1,
    // but that's no problem for us. A small price to pay for
    // linear O(target) time and space complexities.
    // We now loop through arrivalTimesByPosition backwards, i.e.
    // in order of cars initially closest to the target to those
    // furthest away
    let fleetAheadArrivalTime = -1;
    let numFleets = 0;
    for (let i = arrivalTimesByPosition.length - 1; i >= 0; i--) {
    const arrivalTime = arrivalTimesByPosition[i];
    if (arrivalTime

  • @СергейЛюбимов-у3ф
    @СергейЛюбимов-у3ф 25 วันที่ผ่านมา

    This problems seems hard at first, because it obfuscates the "meat" of the problem with considerations for arrival time, position of the car if it catches up and so on. While in reality, you can solve it just by counting arrival time and increasing the fleet_counter when you got slower time

  • @nguyen-dev
    @nguyen-dev 2 ปีที่แล้ว

    We don't need a stack. We only need to keep track indices of 2 cars and check if these 2 cars can meet before the target. So, space complexity is O(1).

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

    Very difficult concept but easy and short for codes, amazing.

  • @oldumvolley
    @oldumvolley 3 หลายเดือนก่อน

    Thank you for all your content!
    I would advise you to emphasize the word 'not' more when forming a negative statement while talking, as I got confused at some point.
    btw
    No stack.pop() solution:
    def carFleet(target: int, position: list, speed: list[int]) -> int:
    fleets_stack = []
    pairs = [(p, s) for p, s in zip(position, speed)]
    for p, s in sorted(pairs, reverse=True): # descending by position (the first el in the tuples)
    trt = (target - p) / s # current t-ime to r-each the t-arget
    if fleets_stack and fleets_stack[-1] >= trt:
    continue
    fleets_stack.append(trt)
    return len(fleets_stack)

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

    There is no need for a stack to solve this problem, you can just track the number of fleets and the last arrival, as you only ever look at the top of the stack.
    If when you see a car, you only add it to the stack when its arrival time is larger than the previous arrival time, you will never pop from the stack. An append only list on which you only ever look at the last element is just a variable.

  • @АртёмКурышкин-ж8ъ
    @АртёмКурышкин-ж8ъ 4 หลายเดือนก่อน

    Thanks a lot for the video, but I don't understand the while instead of if.
    If we will use the example described below, the answer with if for it will be 2, but the correct answer is 1
    (3, 3), (5,2), (7,1), (8,1), target = 12

  • @FreeStuff4TheWorld
    @FreeStuff4TheWorld 2 ปีที่แล้ว +16

    I guess you could call this one fleetcode
    heh

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

    You make these questions look so easy, great explanation.
    Thank you so much!

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

    Never would have thought of this.

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

    Without stack
    class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    pairs = [[pos,spe] for pos, spe in zip(position, speed)]
    prev_time = None
    res = 0
    for pos,speed in sorted(pairs)[::-1]:
    cur_time = (target-pos)/speed
    if not(prev_time and cur_time

  • @AlexRoy-h9s
    @AlexRoy-h9s หลายเดือนก่อน

    I just went super geek mode and google if pair.reverse( ) and pair[ : : -1] have the same time complexity in python and realized that pair.reverse( ) is done in O(1) space complexity while [ : : -1] is done in O(n) space complexity in python (Both have the same time complexity). So it would be technically more efficient to use pair.reverse( ) instead of pair[ : : -1], but for this problem it is not that much relevant. I couldn't come up with this solution so thank you very much for making this video explaining it super well. Always a huge fan of this channel. Please don't misunderstand my comment as trying to teach you or find faults in your code. I just was curious 😅

  • @karandeepparashar9310
    @karandeepparashar9310 2 ปีที่แล้ว +20

    Is it not that the time complexity is O(n*logn) instead of linear time as we sorted the array as well?

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

      Yeah i saw that python sorted() on the entire array is O(nlogn) ...

    • @_carrbgamingjr
      @_carrbgamingjr 3 หลายเดือนก่อน

      11:00

  • @jideabdqudus
    @jideabdqudus 3 ปีที่แล้ว +7

    Wonderfully explained, keep it going neet 💯💯

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

    It's also possible to solve this in O(n + target). It depends on the input but wouldn't this be preferrable compared to O(nlogn)? Here's the code:
    class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    road = [None] * (target + 1)
    for i, pos in enumerate(position):
    road[target - pos] = (pos, speed[i])
    road = [v for v in road if v is not None]
    last = None
    res = 0
    for pos, vel in road:
    t = (target - pos) / vel
    if last is None or t > last:
    last = t
    res += 1

    return res

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

    You will need a float(target-p) / s to get the right answer
    Debugged the hard way when I was presented with the input target = 10, position = [6,8], speed = [3,2]. Output = 1, expected = 2
    class Solution(object):
    def carFleet(self, target, position, speed):
    """
    :type target: int
    :type position: List[int]
    :type speed: List[int]
    :rtype: int
    """
    pair = [[p,s] for p, s in zip(position, speed)]
    stack = []
    for p,s in sorted(pair)[::-1]:
    stack.append(float(target - p) / s)
    if len(stack) >= 2 and stack[-1]

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

      class Solution:
      def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:

      Stuple = zip(position,speed)
      dict1 = dict(Stuple)
      dict2 = {}
      srd = sorted(dict1.items(), key= lambda x:x[0])
      if len(srd) == 1:
      return 1
      result = []
      for i in range(len(srd)-1,-1,-1):
      result.append((target-srd[i][0])/srd[i][1])
      if len(result) > 1 and result[-1]

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 2 ปีที่แล้ว

      Why do u need float() when single '/' already gives float division

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

      @@VarunMittal-viralmutant yea at first I left it as - (target - p) / s - and later it failed some test cases. Naturally regardless of interview or not, I wouldn’t code in the float() part unless I get different values. Let us know if it worked for u! Thanks!

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 2 ปีที่แล้ว

      @@edwardteach2 Ofcourse it works without float(). Not sure which testcase failed for you

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

      There is a difference in py2 vs py3 in the way `/` works. `3/2` returns 1 (int) in py2 but 1.5 (foat) in py3.

  • @hardiksinghal1360
    @hardiksinghal1360 2 หลายเดือนก่อน +1

    This problem was asked in my interview and I couldn't solve it and now I'm here just to understand how to do it

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

    you are my knight in shining armour! thanks once again!

  • @AniruddhaShahapurkar-wu3ed
    @AniruddhaShahapurkar-wu3ed 10 หลายเดือนก่อน

    A little modified version:
    class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    pair = [(p, s) for p, s in zip(position, speed)]
    pair.sort(reverse=True)
    stack = []
    for position, speed in pair:
    travel_time = (target - position) / speed
    if not stack or travel_time > stack[-1]:
    stack.append(travel_time)
    return len(stack)
    Note: We are appending to stack only when the car will be a part of a different fleet, as we have to return the number of fleets.
    # Eventually, every car will reach the destination any ways, we just need to figure out how many fleets we can form

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

    Awesome, great explanation! However, I think this can be done without using the stack as well.

  • @nizarahamed.m1004
    @nizarahamed.m1004 ปีที่แล้ว +1

    They havent mentioned time for float values.We should only check for time if they collide or not in whole values.

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

    Your explanation is golden

  • @RivaldiANS
    @RivaldiANS 4 หลายเดือนก่อน

    here is the modified solution without the need to do sorting based on the solution provided in the video (although this is slower compared to the solution provided by neetcode when I submitted this on leetcode)
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    hashmap = {}
    stack = []
    for i in range(len(position)):
    hashmap[position[i]] = speed[i]
    for i in range(target - 1, -1, -1):
    if i not in hashmap:
    continue

    stack.append((target - i) / hashmap[i])
    if len(stack) >= 2 and stack[-1]

  • @Acel-01
    @Acel-01 ปีที่แล้ว

    The best explanation I've watched on your channel so far. Damn!

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

    I came out a slightly faster solution, hope that helps:
    class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    pos_spd_pair = [(pos,spd) for pos, spd in zip(position, speed)]
    pos_spd_pair.sort(reverse=True)
    stack = [pos_spd_pair[0]]
    for pos, spd in pos_spd_pair[1:]:
    pos_car_ahead, spd_car_ahead = stack[-1]
    # if time to arrive at the destination is shorter, will merge
    if (target-pos) / spd

  • @gmhussein
    @gmhussein 4 หลายเดือนก่อน

    This one was surprisingly intuitive for me...

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

    this is a great way to look at this problem.

  • @akshaychavan5511
    @akshaychavan5511 9 หลายเดือนก่อน

    We don't really need a stack to solve this problem. The approach remains the same but without using a stack.
    Here's a python implementation for it -
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    pair = [[pos, speed] for pos, speed in zip(position, speed)]
    prevMaxTime = float('-inf')
    counter = 0
    for pos, speed in sorted(pair, reverse = True):
    time = (target - pos)/speed
    if (target - pos)/speed > prevMaxTime:
    prevMaxTime = time
    counter += 1
    return counter

  • @horrorcrave
    @horrorcrave 8 หลายเดือนก่อน

    No stack is actually needed. Here is another way:
    class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    cars = sorted(zip(position, speed), reverse=True)
    fleets = 0
    last_t = 0
    for (p, s) in cars:
    t = (target - p) / s
    if t > last_t:
    fleets += 1
    last_t = t
    return fleets

  • @last-life
    @last-life 10 หลายเดือนก่อน

    Flavortown -
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    sorted_fleet = sorted(zip(position, speed), reverse=True)
    fleets = []
    for p, s in sorted_fleet:
    time = (target - p) / s

    if not fleets or time > fleets[-1]:
    fleets.append(time)
    return len(fleets)

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

    Congratulations! Good explanation!!!

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

    Many congratulations on 100K!!! you totally deserve it and more :)

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

      are you talking about his subs or his salary?=)

  • @krishankantray
    @krishankantray 6 หลายเดือนก่อน

    not strictly a stack problem, but yeah can be solved using stack.

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

    Never imagined that we had to use the physics formula for time

    • @PIYUSH-lz1zq
      @PIYUSH-lz1zq 2 ปีที่แล้ว

      why we are not counting whenever stack[-1]

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

      ​@@PIYUSH-lz1zq the top of the stack is meant to represent the slowest car fleet at the time, so every time you add to the stack and don't pop you are adding an even slower car fleet which can't collide with the previous slowest. That's why we can return the length of the stack bc it's going to be the car fleets that didn't collide. We pop because when we find a faster car, we take it out and treat it like it's merged with the slowest car fleet at the previous stack top.

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

    No need to use a stack
    def carFleet(target: int, position: List[int], speed: List[int]) -> int:
    n = len(position)
    cars = sorted(zip(position, speed), reverse=True)
    max_time = 0
    fleets = 0
    for pos, spd in cars:
    time = (target - pos) / spd
    if time > max_time:
    max_time = time
    fleets += 1
    return fleets

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

      yep this is prob the best solution, but can also be implemented as a stack which was more intuitive for me but of course higher space complexity.
      cars = [(pos, spd) for pos, spd in zip(position, speed)]
      cars.sort(reverse=True)
      stack = []
      for i in range(len(cars)):
      time = (target - cars[i][0]) / cars[i][1]
      if len(stack) > 0 and time > stack[-1]:
      stack.append(time)
      if len(stack) == 0:
      stack.append(time)
      return len(stack)

  • @AlexzDum-6174
    @AlexzDum-6174 2 ปีที่แล้ว +1

    you really don't need a stack to solve this. Sorting is the key and then go in reverse

  • @li-xuanhong3698
    @li-xuanhong3698 3 ปีที่แล้ว +1

    Love it ! Thanks for keeping post new videos

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

    the explanation for the problem was really awesome!

    • @PIYUSH-lz1zq
      @PIYUSH-lz1zq 2 ปีที่แล้ว

      why we are not counting whenever stack[-1]

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

    Why stack just sort the array in descending order of position and use two pointer approach

    • @poketopa1234
      @poketopa1234 8 หลายเดือนก่อน

      I also thought of this. I think it works, but I haven't tested it yet.

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

    i LOVE YOU NEETCODE!

  • @snowkey7186
    @snowkey7186 3 หลายเดือนก่อน

    That orange must get a speeding ticket. Jokes aside, thank you for the video man.

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

    Explanation is top!

  • @sajeeree
    @sajeeree 3 ปีที่แล้ว +7

    Since you are taking sorted pair, you probably will endup time complexity as nlogn, Did I miss anything?

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

      I am wondering why nobody said this before. Any answer about that? If you need to sort them, you'll not getting a O(n). Or did I missed smthing?

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

      Oops, he mentioned it on 10:54

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

    Your explanation is the best. I tried to ask chatGPT to give me hints. It didn't succeed. My js solution (not the best)
    var carFleet = function(target, position, speed) {
    if (position.length === 1) return 1;

    const sorted = position.map((el,i) =>({p: el, v:speed[i]}) ).sort((a, b) => b.p - a.p);
    let stack = [sorted[0]];

    for (let i = 1; i < sorted.length; i++) {
    const current = sorted[i];
    const last = stack[stack.length-1];

    const currentReachTime = (target - current.p) / current.v;
    const lastReachTime = (target - last.p) / last.v;
    if (currentReachTime > lastReachTime) {
    stack.push(current);
    }

    }

    return stack.length;
    };

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

    It is only linear if the cars are given in sorted order.

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

      Yeah that's correct

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

    Damn, this marks the first time I failed to understand your solution even after multiple watches, so I had to look elsewhere. Turns out this problem is just a pain to implement in C++.

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

    Awesome explanation. Thanks a lot.

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

    Really like your explanation!

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

    The singular of "axes" is "axis"

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

    man thanks alot, this was really understandable

  • @chowdhuryan-noor2673
    @chowdhuryan-noor2673 10 หลายเดือนก่อน

    Does anyone else think that this problem would be much better if they gave cars in sorted order? The question specifically states that it is a single lane road and cars cannot overtake one another. So when I saw test cases that didn't have car positions in order I got really confused and thought I was misunderstanding the problem somehow.

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

    Thank you so much. Very well explained.

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

    Was a genius solution. very nice

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

    Hi. Amazing explanation, as usual! But with all due respect, a stack is absolutely unnecessary here. Can easily be done with two plain vars instead, therefore with O(1) memory. Overall I think the problem more fit into "Arrays and Hashing" category then in "Stack".

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

    we dont need list comprehension rather
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
    data = list(zip(position, speed))
    fleets = curr_time = 0
    for pos, sp in sorted(data)[::-1]:
    destination_time = (target-pos)/sp
    if destination_time < curr_time:
    cur_time = destination_time
    fleets += 1
    return fleets

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

      You can call sorted directly on the zip iterator, you don't need to explicitly convert it to a list

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

    Awesome explanation!

  • @tejas8211
    @tejas8211 3 หลายเดือนก่อน

    I used to solve much harder physics problems when i was preparing for iitjee lol. Now this problem is looking hard to me. How times change

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

    That was really good, thank you!!!

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

    this solution is so dope

  • @engineering-maths
    @engineering-maths ปีที่แล้ว

    Sir the time complexity of this solution is O(nlogn) not O(n) because we use sorted() function in the solution and it's time complexity is O(nlogn)

    • @DankMemes-xq2xm
      @DankMemes-xq2xm 6 หลายเดือนก่อน

      he mentions that in the video

  • @akshaydusad6642
    @akshaydusad6642 8 หลายเดือนก่อน

    This problem would be such a headache to understand in interviews

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

    very great solution,mind blown

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

    # Solution in C++
    class Solution {
    public:
    int carFleet(int target, vector& position, vector& speed) {
    vector ans;
    stack st;
    int n = speed.size();
    for(int i=0; i=0; i--){
    double time = (target - ans[i].first) / ((double) ans[i].second);
    if(st.empty() || st.top() < time){
    st.push(time);
    }
    }
    return st.size();
    }
    };

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

    Well explained.