Maximum Swaps - Leetcode 670 - Python

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

КОМЕНТАРІ • 62

  • @gavinebenezer1670
    @gavinebenezer1670 4 дні тому +20

    Beats 69.69% of users in runtime is diabolical

    • @tarifm3881
      @tarifm3881 4 дні тому

      what about beats 100% users 😂 i dont know how their algo works

    • @tarifm3881
      @tarifm3881 4 дні тому

      class Solution {
      public int maximumSwap(int num) {
      char[] s = Integer.toString(num).toCharArray();
      //using post max array
      int[] max = new int[s.length];
      max[s.length-1] = s.length-1;
      for(int i = s.length-2; i>=0; i--){
      if(s[i]>s[max[i+1]]){
      max[i] = i;
      }else{
      max[i] = max[i+1];
      }
      }
      for(int i=0; i

  • @as-zg6
    @as-zg6 5 днів тому +5

    "tell me why?" this cant be swapped ---was very needed sir

  • @chaitanyayeole4111
    @chaitanyayeole4111 4 дні тому +8

    Leetcode is crazy, it passed my O(n^2) solution which beats 96.08%🤣🤣🤣

    • @nexovec
      @nexovec 4 дні тому +1

      The inputs are 4 to 8 digits, the complexity doesn't matter.

    • @kgCode658
      @kgCode658 4 дні тому

      i mean the max no is of 9 digits so its just 9 * 9 ie 81.. lolzz

    • @qulinxao
      @qulinxao 4 дні тому

      just 5 line yield brute forse couse O(9**2): class Solution: def maximumSwap(c, _: int) -> int: def c():#brute force couse b

  • @lost-wind443
    @lost-wind443 5 днів тому +11

    Thank you, everytime I see one of this, I get so excited. ;)

  • @bigfactsbroski
    @bigfactsbroski 4 дні тому

    Seems like extra work at the one pass soln. My algorithm:
    - set best to original number
    - set max to rightmost digit
    - iterate right to left
    - update max if necessary
    - at every element, if max> el, swap max and el and set best (greatest value)
    - return best after loop

    • @bigfactsbroski
      @bigfactsbroski 4 дні тому

      Nvm his is more efficient now that I think on it more

  • @PanchalHappy
    @PanchalHappy 4 дні тому

    Your solutions are intuitive.Thanks

  • @shibambiswas
    @shibambiswas 4 дні тому

    Just changed if-if to if-elif and got 100% in runtime performance.

  • @Ahmad-h3z1v
    @Ahmad-h3z1v 4 дні тому

    was gonna use a heap for some reason spent 30 mins tryna implement it but then got it. thank you

  • @RK-cd
    @RK-cd 4 дні тому +2

    it is crazy I had 100.00% tc.... LC is funny

  • @bandarupawankumar7549
    @bandarupawankumar7549 4 дні тому

    I tried the 2 pass approach after watching this n leetcode gave beats 100% of users, to it

  • @darksca1804
    @darksca1804 5 днів тому +7

    69.69%
    Nicecode

  • @ToonDubberDuo
    @ToonDubberDuo 4 дні тому +2

    why dont you give the optimal solution

  • @ashleywilkonson386
    @ashleywilkonson386 5 днів тому +13

    Technically all the solutions you had would be constant time due to the input being an integer.

    • @prajwals8203
      @prajwals8203 5 днів тому +1

      Exactly..... i wanted to comment the same thing

    • @FlutterInsights
      @FlutterInsights 4 дні тому +1

      I believe despite the input being an integer dose not change the fact that it was converted into string of chars and stored in num which is will take O(n) time, which later is iterated to run the swapping logic on each number on the list already counts as a linear run time along with the join at last when returning the number. Therefore, this solution has three steps which takes O(n) time complexity [O(n) + O(n) + O(n) = O(n)]. So this solution has O(n) time complexity.

    • @FlutterInsights
      @FlutterInsights 4 дні тому

      List of characters*

    • @ashleywilkonson386
      @ashleywilkonson386 4 дні тому

      @@FlutterInsights doesn’t matter, the length of the string has an upper bound of 10-20 characters based on the type of integer. So it’s O(20) -> O(1)

    • @FlutterInsights
      @FlutterInsights 3 дні тому

      @ashleywilkonson386 let's go back to basics right, so when the algorithm runs on constant time regardless of an inpute size then we can say that the algorithm has the time complexity of O(n). For eg: let's say there's a function which takes an array of integers of size 1000 but it only returns the specified index arr[12] then it's a constant time regardless of it input size upper bound which is 1000. But let's say if we're trying to find the maximum integer from the array then we need to iterate through each elements of array which means if we go by brut force we will be iterating 1000 times. So here's the difference our first problem only needs to access specifid index of array and return and latter requires to find the max integer, first solution doesn't depend on the input size but latter depends on the input size as we need to loop through the array to get to our expected output. Therefore, the solution on this video takes O(n) time to solve the problem.

  • @qulinxao
    @qulinxao 4 дні тому

    just 5 line yield brute forse couse O(9**2): class Solution: def maximumSwap(c, _: int) -> int: def c():#brute force couse b

  • @wintersijan
    @wintersijan 5 днів тому +1

    Can you make a video on greedy algorithm with multiple example ? I already have neetcode premium but couldn't find any video on this one?

  • @ap2s2000
    @ap2s2000 5 днів тому +4

    Just curious -- how did you know the problem of the day so quickly?

    • @aizad786iqbal
      @aizad786iqbal 5 днів тому +3

      brute force, he has these problems pre solved..

    • @ap2s2000
      @ap2s2000 5 днів тому

      @@aizad786iqbal not the optimal solution ...

    • @prajwals8203
      @prajwals8203 5 днів тому +1

      QID Question name Asked Date
      349 Intersection Of Two Arrays
      632 Smallest Range Covering Elements From K Lists 2024-10-13
      641 Design Circular Deque
      930 Binary Subarrays With Sum
      962 Maximum Width Ramp 2024-10-10
      1105 Filling Bookcase Shelves
      1233 Remove Sub Folders From The Filesystem
      1277 Count Square Submatrices With All Ones
      1608 Special Array With X Elements Greater Than Or Equal X
      1671 Minimum Number Of Removals To Make Mountain Array
      1942 The Number Of The Smallest Unoccupied Chair 2024-10-11
      2044 Count Number Of Maximum Bitwise Or Subsets
      2406 Divide Intervals Into Minimum Number Of Groups 2024-10-12
      2416 Sum Of Prefix Scores Of Strings
      2458 Height Of Binary Tree After Subtree Removal Queries
      2463 Minimum Total Distance Traveled
      2530 Maximal Score After Applying K Operations 2024-10-14
      2664 The Knights Tour
      2742 Painting The Walls
      2838 Maximum Coins Heroes Can Collect 2024-10-08
      1593 Split A String Into The Max Number Of Unique Substrings
      1963 Minimum Number Of Swaps To Make The String Balanced 2024-10-08
      2938 Separate Black And White Balls 2024-10-15
      921 Minimum Add To Make Parentheses Valid 2024-10-09
      1106 Parsing A Boolean Expression
      670 Maximum Swap 2024-10-17
      1405 Longest Happy String 2024-10-16
      2583 Kth Largest Sum In A Binary Tree
      1545 Find Kth Bit In Nth Binary String
      687 Longest Univalue Path
      968 Binary Tree Cameras
      841 Keys And Rooms
      Now even you know

    • @adi_cs03
      @adi_cs03 4 дні тому

      @@prajwals8203 where did you get this list?

  • @akshayvishwakarma188
    @akshayvishwakarma188 5 днів тому +2

    Thanks Neetcode, btw anyone wrote the 2pass solution? I was trying to write it. In java but i am confused

    • @kevinjoythomas6528
      @kevinjoythomas6528 4 дні тому

      class Solution {
      public:
      int maximumSwap(int num) {
      string numStr = to_string(num);
      int n = numStr.size();
      vector maxRightIndex(n); // Stores the index of the max digit from
      // current position to the end
      // First pass: Populate maxRightIndex with the index of the largest
      // digit to the right of each position
      maxRightIndex[n - 1] = n - 1;
      for (int i = n - 2; i >= 0; --i) {
      maxRightIndex[i] = (numStr[i] > numStr[maxRightIndex[i + 1]])
      ? i
      : maxRightIndex[i + 1];
      }
      // Second pass: Find the first place where we can swap to maximize the
      // number
      for (int i = 0; i < n; ++i) {
      if (numStr[i] < numStr[maxRightIndex[i]]) {
      swap(numStr[i],
      numStr[maxRightIndex[i]]); // Swap to maximize the number
      return stoi(numStr); // Return the new number immediately after
      // the swap
      }
      }
      return num; // Return the original number if no swap can maximize it
      }
      };

  • @addiegupta
    @addiegupta 4 дні тому

    great to see the wrong solution as well thanks a lot for that ! really gives us insight

  • @Pegasus02Kr
    @Pegasus02Kr 4 дні тому

    I think Im completely fine with 2path solution

  • @rajsuriyang3427
    @rajsuriyang3427 4 дні тому

    class Solution:
    def maximumSwap(self, num: int) -> int:
    str_num=list(str(num))
    lst=[(-int(e),i) for i,e in enumerate(str_num)]
    heapq.heapify(lst)
    swap=False
    i=0

    while lst:

    digit,indx=heapq.heappop(lst)
    digit=digit*-1


    if int(str_num[i])==digit:
    i+=1

    else:
    ind=-1
    while lst and -lst[0][0]==digit:
    _,ind = heapq.heappop(lst)
    if ind != -1:
    indx=ind
    print(str_num[indx],str_num[i],i,indx)
    str_num[i],str_num[indx]=str_num[indx],str_num[i]
    break
    return int("".join(str_num))
    help me is it OK?

  • @lakshay1168
    @lakshay1168 4 дні тому

    why can't it be solved using the max_heap? please do help me wrote code which is passing the sample test cases and giving the correct output for text case no-77 while doing DRY RUN but giving the wrong output

  • @nexovec
    @nexovec 4 дні тому

    BEATS 100% OF USERS. 💪🎸💢

  • @AlthafNazeer-n3m
    @AlthafNazeer-n3m 4 дні тому

    My solution :)
    class Solution:
    def maximumSwap(self, num: int) -> int:
    if str(num) == sorted(str(num)) or num < 10:
    return num
    items = [i for i in str(num)]
    new_items = sorted(items)[::-1]
    i = 0
    while i < len(items):
    if new_items [i] != items[i]:
    val = items[i]
    req = max(items[i : ])
    for j in range(len(items) - 1, i , -1 ):
    if items[j] == req:
    idx = j
    break
    items[i], items[idx] = items[idx], items[i]
    break
    else:
    i += 1
    return int("".join(items))

  • @sidsomani8578
    @sidsomani8578 4 дні тому

    this is my code for two paths im passing 105/112 cases can anyone help me figure out why this isnt working please?
    class Solution:
    def maximumSwap(self, num: int) -> int:
    number = [int(n) for n in str(num)]
    print(number)
    max_val = 0
    max_index = number.index(max(number))
    max_arr = [0 for n in number]
    # R -> L storing max array
    for i in range(len(number)-1, -1, -1):
    if number[i] > max_val:
    max_val = number[i]
    max_index = i
    max_arr[i] = max_val
    # L -> R to check all values to the left of max_index
    for i in range(max_index):
    if number[i] < max_val:
    temp = number[i]
    number[i] = max_val
    number[max_index] = temp
    break
    out = ""
    for n in number:
    out += str(n)
    return int(out)

  • @AneesMd-di6pr
    @AneesMd-di6pr 5 днів тому

    6:48 we can still keep the track of maxvalue post the index by updating the maxvalue right before the inner loop starts
    for(int j =0;jj;i--){
    if(s[i]-'0' > s[maxindex]-'0')
    maxindex = i;
    }
    if(s[maxindex]-'0' > s[j]-'0'){
    var t = s[maxindex];
    s[maxindex] = s[j];
    s[j] = t;
    break;
    }
    }

  • @vedanthbaliga7686
    @vedanthbaliga7686 5 днів тому

    is the neetcode website down?

    • @NeetCodeIO
      @NeetCodeIO  5 днів тому

      Only for certains ISPs in India. This is an issue with firebase hosting, use neetcode.dev for now please

  • @rajGg-h3g
    @rajGg-h3g 5 днів тому +1

    class Solution:
    def maximumSwap(self, num: int) -> int:
    s = str(num)
    sorted_s = ''.join(sorted(s, reverse=True))
    r = list(s)

    for i in range(len(sorted_s)):
    if sorted_s[i] != r[i]:
    c = sorted_s[i]
    d = r[i]
    r[i] = c
    for j in range(len(sorted_s) - 1, -1, -1):
    if c == r[j] and j != i:
    r[j] = d
    break
    break

    return int(''.join(r))
    Is this good or not ? 😊

    • @AlfredPros
      @AlfredPros 4 дні тому

      This solution would work, however the bottleneck of this algorithm is the sorting on the start because it takes O(nlogn). A way to optimize this would be to change the sort to a max heap. heapq.heapify function takes O(n) time, which is faster.

    • @rajGg-h3g
      @rajGg-h3g 4 дні тому

      @@AlfredPros Actually , the largest number is of length is 9 digit so n=9 in this case, am i right ? So it works in O(1) may be

    • @AlfredPros
      @AlfredPros 4 дні тому

      @@rajGg-h3g n in this case is the digit of num. I thought about the algorithm as general as possible, that's why I said the sorting time is O(nlogn). Since the problem only have 9 digits at maximum, the time difference may not be so apparent at the end.

  • @nofollowrobotstxt
    @nofollowrobotstxt 5 днів тому

    mid

  • @Gojo-hl7iu
    @Gojo-hl7iu 5 днів тому

    dofm mgsd g somng m

    • @brij4887
      @brij4887 4 дні тому

      I too had a stroke when I tried to solve this problem

  • @siliconhawk
    @siliconhawk 4 дні тому +1

    bro I wrote a 50 line monstrosity. with 2 helper function. and finally it worked OR SO I THOUGHT. but damn there were like 1 test cases which fuked me up fixed it then it broke some other test case best result was 110/112 . wasted 2 hours, kinda solved it but it failed. here i am
    EDIT - here is the monstrosity if anyone is interested Do NOT ask me what it is or how it works, coz i myself forgot what this is supposed to do.
    ```
    class Solution {
    public:
    int firstNonDecreasingIndex(string s) {
    for (int i = 0; i < s.length() - 1; i++) {
    if (s[i] front1; i--) {
    if (s[i] > a) {
    a = s[i];
    }
    }
    return a;
    }
    int maximumSwap(int num) {
    string intnum = to_string(num);
    string temp = intnum;
    int currgreatest = num;
    int front = 0, back = intnum.size()-1;
    char sl = greatestInt(intnum);
    int i = intnum.size()-1;
    for (int i = temp.size() - 1; i >= 0; i--) {
    if (temp[i] == sl) {
    back = i;
    break;
    }
    }
    while(front < back){
    if (temp[front] < temp[back]){
    swap(temp[front], temp[back]);
    }
    int test = stoi(temp);
    if(test > currgreatest){
    currgreatest = test;
    }
    temp = intnum;
    front++;
    }
    return currgreatest;
    }
    };
    ```

    • @adi_cs03
      @adi_cs03 4 дні тому

      check out the monstrosity i first wrote:
      class Solution {
      public:
      int findRightMostGreatestChar(const string &str, int startIdx, int endIdx) {
      if (startIdx < 0 || endIdx >= str.length() || startIdx > endIdx) {
      return -1; // Invalid range
      }
      char baseChar = str[startIdx]; // Set base char as str[startIdx]
      int resultIdx = -1; // To store the index of the rightmost greatest char
      char maxChar = baseChar; // Initially set maxChar as baseChar
      // Traverse the substring from startIdx to endIdx (right to left)
      for (int i = endIdx; i > startIdx; --i) {
      if (str[i] > maxChar) {
      maxChar = str[i]; // Update maxChar to the current greatest character
      resultIdx = i; // Update resultIdx to the rightmost index of the greatest character
      }
      }
      return resultIdx; // Return the index of the rightmost greatest character
      }
      int maximumSwap(int num) {
      string number = to_string(num);
      //if digits are in descending order, no greater number is possible
      if( is_sorted( number.rbegin() , number.rend())){
      return num;
      }
      //if digits are in ascending order, greatest digit is at last, swap it with first element
      if( is_sorted(number.begin(), number.end())){
      swap( number[number.length() - 1] , number[0]);
      return stoi(number);
      }
      //we need to bring the rightmost max digit to left most index possible
      //if the starting digits of the numbers are maximum, we dont have to swap them
      for(int i = 0; i

    • @qulinxao
      @qulinxao 4 дні тому

      just 5 line yield brute forse couse O(9**2): class Solution: def maximumSwap(c, _: int) -> int: def c():#brute force couse b

    • @KTLO-m8p
      @KTLO-m8p 3 дні тому

      Sus