Coding Interview Problem - Car Fleet

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

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

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

    Great explanation thanks!

  • @SS-cz3vg
    @SS-cz3vg ปีที่แล้ว

    Amazing explanation and so easy to understand.

  • @noble.things
    @noble.things 9 หลายเดือนก่อน

    Thanks so much for the excellent explanation of the problem. It really crystallized it for me. That being said, it seems there might be a bug in the code though. In the case where there are no collisions (i.e. no car catches up to another car), the resulting fleet count should be the total number of cars (since each individual car is a fleet), but based on this code, it will be 1. Disclaimer: I didn't actually run the code, but just from looking at it, "fleet_count" is initialized to zero and incremented only when there's a collision, and once again after exiting the "for" loop. Unless I’m missing something….

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

    Keep it up! May I recommend you discuss the solution to the "Longest Substring with At Least K Repeating Characters" problem (lc #395)? Specifically, the sliding window approach, as the divide-and-conquer approach is trivial

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

    Insane explanation thanks Brother 🎉

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

    Super!!

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

    I finally managed to make my own implementation in java with my limited programming knowledge haha
    import java.util.Arrays;
    public class CarFleet {
    public static void main(String[] args) {
    int carDistance = 12;
    int[] carPositions = {2, 0, 4, 7};
    int[] carSpeeds = {4, 1, 2, 1};
    System.out.println(countCarFleets(carDistance, carPositions, carSpeeds)); // expected fleets: 2
    }
    public static int countCarFleets(int distance, int[] position, int[] speed) {
    int countFleets = 0;
    int[] carPositions = position.clone();
    int[] carSpeeds = new int[speed.length];
    Arrays.sort(carPositions);
    for(int i = 0; i < carSpeeds.length; ++i)
    {
    int index = Arrays.binarySearch(carPositions, position[i]);
    carSpeeds[index] = speed[i];
    }
    int timeFront = (distance - carPositions[carPositions.length - 1]) / carSpeeds[carSpeeds.length - 1];
    for(int i = carSpeeds.length - 2; i > -1; --i)
    {
    int timeBack = (distance - carPositions[i]) / carSpeeds[i];
    if(timeBack > timeFront)
    {
    ++countFleets;
    timeFront = timeBack;
    }
    }
    return ++countFleets;
    }
    }