How to Find the Median of Two Sorted Arrays (Simple JavaScript Solution) | JavaScript | Carla Codes

Поделиться
HTML-код
  • Опубликовано: 10 янв 2025

Комментарии • 10

  • @kcmi3670
    @kcmi3670 4 года назад +4

    If this question was asked at an interview, I guarantee that this would not be the solution the interviewer would want. This problem was created purely to test logarithmic time complexity.

  • @monles_yen
    @monles_yen 2 года назад

    Thank you! It's awesome

  • @callmechocolateboy
    @callmechocolateboy 4 года назад +3

    good video but can you solve in O(log(m+n)) time complexity ??

    • @user26912
      @user26912 2 года назад

      Yes this algorithm is inefficient (O(N) for concat and O (N lg N) for the sort ). Also the arrays were already sorted so something more faster can be done. Fastest I can think of is looping over length of both arrays combined, keeping a pointer into first array and a pointer in the next, take first value by comparing lowest of first array versus second array, if you take from first array increase first pointer, otherwise the second pointer, and if you are at the end of one of the arrays just take the rest of the remaining array, that would be O(N) worst case. Don't know how it can be done faster.

  • @saicharanreddy8366
    @saicharanreddy8366 3 года назад

    Can anyone explain why function(a,b){return a-b} is used as I am new to coding!

    • @user26912
      @user26912 2 года назад

      It sorts the array from low to high. sort() can take a comparator function as an argument. A comparator takes two values a and b, if a should be regarded higher it should return a positive value, if it is equal it should return 0, and if b should be regarded higher it should return a negative value. So (a, b) => a - b is a function that sort by ascending order. Note that default behaviour of sort() is to do string comparisons... So an array 1, 3, 5, 33 would be sorted as 1, 3, 33, 5. By using sort((a, b) => a - b) you get 1, 2, 3, 5, 33 instead.

  • @yasern4227
    @yasern4227 4 года назад +1

    Very well explained!! Please solve more complex problems.

    • @givemeabreak2469
      @givemeabreak2469  4 года назад

      Thank you! More videos like this are coming soon!

  • @トモヤ-x1n
    @トモヤ-x1n 3 года назад

    This is fine if the given arrays are not sorted in terms of time complexity....

  • @gyanasahu1006
    @gyanasahu1006 4 года назад +1

    not the optimal solution