Single Number - Leetcode 136 - Python

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

КОМЕНТАРІ • 111

  • @NeetCode
    @NeetCode  2 роки тому +3

    Python Code: github.com/neetcode-gh/leetcode/blob/main/136-Single-Number.py
    Java Code (from a viewer - ndesai): github.com/ndesai15/coding-java/blob/master/src/com/coding/patterns/bitwiseXOR/SingleNumberXOR.java

  • @blairbass84
    @blairbass84 2 роки тому +131

    One huge point that is missing from this explanation that may help others (like myself) who were previously unfamiliar with XOR: the XOR operation is associative and commutative. That means a ^ (b ^ c) = (a ^ b) ^ c, and a ^ b = b ^ a. From these two properties, we can see that ((((4 ^ 1 ) ^ 2 ) ^ 1 ) ^ 2 ) = (2 ^ 2) ^ (1 ^ 1) ^ 4. The left hand side of this equation is what the solution code is effectively doing. On the right hand side, we can take the basic XOR operation principles discussed in the video to see that it equals 0 ^ 0 ^ 4 = 0 ^ 4. Since n ^ 0 = n, then we know that the answer is 4.

    • @davepassaro8366
      @davepassaro8366 2 роки тому +2

      cheers

    • @ardenmaalik6156
      @ardenmaalik6156 2 роки тому +5

      Thanks, this definitely cleared it up for me.

    • @emirhandemir3872
      @emirhandemir3872 Рік тому +3

      Thanks a lot man. I have been getting crazy about the fact that the order does not matter. I have been asking myself WWWHHHYYYY !!!!

    • @Ivan-ek6kg
      @Ivan-ek6kg Рік тому +1

      Thanks a lot, I am just about to search it!

    • @butoyighyslain171
      @butoyighyslain171 Рік тому +2

      this is the exact bit I was missing! thanks :)

  • @CostaKazistov
    @CostaKazistov 2 роки тому +42

    Simply brilliant!
    This is the best channel for LeetCode walkthroughs on UA-cam.
    The way you explain how to develop intuition for this problem is truly next level.

  • @DanhWasHere
    @DanhWasHere 2 роки тому +102

    Another example of a "Crackhead" problem as NeetCode described before -like the video says and the comments say, only people who encountered this problem would think to XOR first.

    • @leonscander1431
      @leonscander1431 3 місяці тому

      Disagree.
      I saw it for the first time and came up with XOR solution.
      4 1 2 1 2
      My logic was like this:
      If we could sum the first three numbers:
      4 + 1 + 2 = 7
      And then somehow subtract the rest (duplicates):
      7 - 1 - 2 = 4
      We would have that unique number left.
      And then I thought of XOR.

    • @ah_sheta
      @ah_sheta 2 місяці тому

      @@leonscander1431 I also thought about adding and subtracting, but why did you thought of XOR after that (I mean.. is there any particular reason)?

    • @servantofthelord8147
      @servantofthelord8147 Місяць тому

      @@ah_sheta I've noticed bit manipulation is like the last resort for a constant space solution. There are a lot of popular problems that can also be solved with bit manip in constant space. But I agree - I couldn't figure out the xor solution lol!

  • @jason1666
    @jason1666 2 роки тому +107

    I wonder if anyone ever intuits this solution out. Seems like a good way to make sure you only pass people who've memorized this solution

    • @j.a.1776
      @j.a.1776 2 роки тому +11

      Perhaps they're looking for a mathematician who can also prove that the solution works xD

    • @MarsTheProgrammer
      @MarsTheProgrammer 2 роки тому +10

      Yup, sometimes it’s just luck during an interview. Luck that you have seen the same or similar problem.

    • @LiveType
      @LiveType 2 роки тому +10

      Similar questions and concepts are taught in basic ass firmware engineering courses because these types of operations are fast and efficient so you get into the habit of approaching every problem this way.
      So I suppose the answer to your question is no unless that's who they were attempting to hire with this question. There's effectively zero chance you would ever "stumble" upon the solution thinking it out unless you are an embedded systems engineer or deal with this type of stuff on a frequent basis.

    • @takeuchi5760
      @takeuchi5760 4 місяці тому +4

      ​​@@LiveType I've taken discrete maths, and a digital logic course just last semester, so XOR is a pretty common thing for me. And, it still didn't ever occur to me that you could xor like a hashSet to get rid of duplicate value, that's very clever.

  • @tahaansari5621
    @tahaansari5621 2 роки тому +13

    Thanks! I was looking for the xor solution.

  • @expansivegymnast1020
    @expansivegymnast1020 Рік тому +4

    Thank you! This is why I'm going through the LeetCode Easy's I still learn things

  • @MonisKhan
    @MonisKhan 2 роки тому +15

    Thanks!

    • @NeetCode
      @NeetCode  2 роки тому +3

      Thank you so much!!

  • @edwythefair5215
    @edwythefair5215 2 роки тому +8

    A difficult concept, thanks a lot!

  • @deVamshi
    @deVamshi 2 роки тому +5

    Your explanation is so good

  • @licokr
    @licokr 7 місяців тому

    I've tried to understand it by myself but I didn't ensure 100%. Organzize all bits and even one bits will be zero and there ends up the number exists once. That's the simplest explanation I could imagine. Thank you so much!

  • @fethanus
    @fethanus 8 місяців тому

    The key point is XOR operation is ASSOCIATIVE. This means
    A ^ B ^ C = C ^ A ^ B so if two operants are same result will be 0.
    0 ^ singleNumber = singleNumber. So we result variable initialized 0

  • @kirillzlobin7135
    @kirillzlobin7135 Рік тому +2

    Amazing, but.... how do you come up to this solutions...?

  • @nikhilgoyal007
    @nikhilgoyal007 Рік тому +1

    thanks! sorry for the basic question but how does the code know that for res = n ^ res, n needs to be changed to binary for this operation ? thanks!

  • @venkatrushivanga1025
    @venkatrushivanga1025 2 роки тому

    Never thought like this it can be solved. Good bro🙂

  • @samlinus836
    @samlinus836 Рік тому

    Brilliant explanation

  • @ZechenGuo-h6t
    @ZechenGuo-h6t Рік тому

    Awesome explanation!

  • @andriidanylov9453
    @andriidanylov9453 Рік тому

    What a cool solution. Love it.👍

  • @LoganLi-su5ju
    @LoganLi-su5ju Рік тому +1

    I come up with this solution by myself! I am clever😁

  • @Deschuttes
    @Deschuttes 2 роки тому +5

    Is this just something you learn in CS classes? I write frontend and never ran into needing to use XOR. I mean, I was aware of its existence.

    • @pizzapanni
      @pizzapanni 2 роки тому +2

      Yes.

    • @nickwilson3499
      @nickwilson3499 2 роки тому

      If you do lower level stuff then you will need it.

    • @joelwillis2043
      @joelwillis2043 Рік тому

      frontend is all you ever need in the universe /s

  • @dustinscroggins6256
    @dustinscroggins6256 2 роки тому +1

    I sorted the numbers then compared pairs !! Would that fit the conditions for the time complexity?

    • @JayGrant
      @JayGrant 2 роки тому +1

      i think array.sort is n(logn) so i dont think so ... if that's what you used.

    • @dustinscroggins6256
      @dustinscroggins6256 2 роки тому

      @@JayGrant ah okay makes sense I was just trying to find another way to solve it

    • @JayGrant
      @JayGrant 2 роки тому

      @@dustinscroggins6256 i understand, this was the first solution that i thought of actually.

  • @grandparick3176
    @grandparick3176 Рік тому +1

    Man I solved this problem using sorting and hashmap but I just couldn't optimize it any further no matter what. I didn't even knew about this method.

  • @marekglowacki2607
    @marekglowacki2607 2 роки тому

    ultra fast and memory lean one-liner: reduce(xor, nums) , reduce from functools, xor from operator

  • @souleymen971
    @souleymen971 Рік тому

    Thank you very much

  • @rodgerdodger17
    @rodgerdodger17 2 роки тому +4

    I was asked this for amazon and completely failed. Went over the problem in my DSA class 4 days later...

    • @appcolab
      @appcolab 2 роки тому +2

      Sorry, if only it came after you learnt it.

  • @3zoabdullah333
    @3zoabdullah333 6 місяців тому

    i solved it like this:
    for index in range(len(nums)):
    if nums.count(nums[index])==1:
    return nums[index]

  • @JonathanJoaquinQuirinoCarrasco
    @JonathanJoaquinQuirinoCarrasco 6 місяців тому

    Wow, very interesting solution man, my solution is the following: def singleNumber(self, nums: List[int]) -> int:

    hash_map = {}

    for num in nums:
    hash_map[num] = 1 + hash_map.get(num, 0)
    for n in hash_map:
    if hash_map.get(n, 0) == 1:
    return n

  • @Douglasfaparanhos
    @Douglasfaparanhos 2 роки тому

    i would never ever think about it

  • @Alexthesurfer
    @Alexthesurfer 8 місяців тому

    return reduce(lambda a, b: a ^ b, nums)

    • @mehdisaffar
      @mehdisaffar 3 місяці тому

      return reduce(operator.xor, nums)

  • @NHCS-ShreyasChaudhary
    @NHCS-ShreyasChaudhary Рік тому

    result=0
    for i in nums:
    result ^= i
    return result

  • @sanooosai
    @sanooosai 2 місяці тому

    thank you

  • @yameenabba7212
    @yameenabba7212 2 роки тому

    Love you man!

  • @ahmedoumar3741
    @ahmedoumar3741 2 роки тому

    Thank you so much!

  • @jy76312
    @jy76312 4 місяці тому

    In the starting you mention for hashset 2 be removed completely. Shouldnt it just be one time

  • @Zarifzar4
    @Zarifzar4 2 роки тому

    Would you consider doing fair indexes Leetcode 1882?

  • @jayeshkaushik2975
    @jayeshkaushik2975 2 роки тому

    What's up bro, ur videos are really helpful thanks 💯

  • @natesgibson
    @natesgibson 2 роки тому

    Is this technically O(1) space? The size of the result variable doesn't scale with the length of the input list, but it does scale with the size of the numbers in the input list.

    • @TB-kx8cc
      @TB-kx8cc Рік тому

      the number of bits allocated for an integer does not change, and even if it did, it wold be O(max(number of bits for all elements of array)) = O(1) since the max is a constant

  • @yashjoon3889
    @yashjoon3889 Рік тому

    Wait isn't the hashset solution O(1) , at any point of time we will only store a single element if we pop out the re-encountered element ?

    • @jacksonnadler-block2869
      @jacksonnadler-block2869 Рік тому +1

      The numbers aren’t in order so we might need to store more and more until we encounter the duplicates

  • @edwardteach2
    @edwardteach2 5 місяців тому

    U a Single Number God

  • @PradeepKumar-zt5nz
    @PradeepKumar-zt5nz 2 роки тому

    Thanks

  • @stephenscott6223
    @stephenscott6223 2 роки тому

    If the unique number is at the end of the array I am getting 0 as the return value. Will have to think of a solution that covers that unless I am missing something here?

  • @zachlandes5718
    @zachlandes5718 6 місяців тому

    Unfortunately, the explanation for the bit manipulation solution about 5 minutes into the video, where you try to show that the solution can be intuited without knowing that XOR is commutative, is wrong. The reason is that it assumes that the unique number is first (or last) in the list. Were the single number in the middle of the list somewhere, there could be an odd number of numbers on either side of it in the list. For example, reorder the list to [1,2,1,4,2]. In this case you would have a single one in the ones column of each group of non-unique numbers, and you'd still have to appeal to the commutative property to cancel out the ones.

  • @jzimmer95
    @jzimmer95 2 роки тому

    Could also use the sliding window algorithm and delete the duplicates as you find them ... index 0 at the end will be your single number

    • @koeber99
      @koeber99 2 роки тому

      The problem states "You must implement a solution with a linear runtime complexity and use only constant extra space."

    • @jzimmer95
      @jzimmer95 2 роки тому

      @@koeber99 my solution is linear and constant! not using extra space as you just delete from the array as you go, and sliding window is about linear time

    • @randomystick
      @randomystick Рік тому

      @@jzimmer95 how do you know a number is a duplicate with constant space and keeping in mind the array can't be sorted (nlogn operation)?

    • @nicoataiza7850
      @nicoataiza7850 Рік тому

      @@jzimmer95 solution that copies the list is o(n) in extra space

  • @sherwancaris5199
    @sherwancaris5199 Рік тому

    Thanx

  • @BurhanAijaz
    @BurhanAijaz Рік тому +1

    what if the repeated numbers were repeated n extra times instead of 2 , eg 3

  • @bashaarshah2974
    @bashaarshah2974 2 роки тому

    Why does
    res = 0
    for i in range(len(nums)):
    res = i ^ res
    return res
    not work? isn't it the same thing?

    • @Ricalrax
      @Ricalrax 2 роки тому +8

      your iterating through the length of the array,(0,1,2,3,4,...,n) instead of the array itself. Good luck!

    • @gustavoadolfodiazcamilo2462
      @gustavoadolfodiazcamilo2462 2 роки тому +1

      The idea is that the same numbers cancel out each other, to do that we need to use XOR only with the numbers on the input array, not with counter "i". `i` could be or couldn't be in the input array.

    • @blairbass84
      @blairbass84 2 роки тому +1

      i represents the array index not the array value. replace "res = i ^ res" with "res = nums[i] ^ res"

  • @RobinHistoryMystery
    @RobinHistoryMystery 6 місяців тому +2

    bit manipulation coding questions should be banned from coding interviews

  • @manikamidha1692
    @manikamidha1692 2 роки тому +1

    for ele in set(nums) :
    if nums.count(ele) == 1 :
    return ele

  • @user-dd7pq2to3o
    @user-dd7pq2to3o Рік тому

    Theres an easier way to do this. The single number is simply: 2*sum(set(nums)) - sum(nums). One line thats faster than 99% of the solutions on leet

    • @ansoribrahim6833
      @ansoribrahim6833 9 місяців тому

      but sum is need too loop over all array, isn't it?

    • @del6553
      @del6553 4 місяці тому +1

      you're creating a set of sums in this case, which uses O(N) space complexity

  • @unitycatalog
    @unitycatalog 2 роки тому

    take an XOR of the elements.

  • @emirhandemir3872
    @emirhandemir3872 Рік тому

    3:34 Please can someone explain this to me. Why does not the order matter ????

    • @ansoribrahim6833
      @ansoribrahim6833 9 місяців тому

      XOR of a number with itself is 0:
      If you XOR a number with itself, the result is always 0.
      For any integer a, a ^ a equals 0.
      This property is crucial for canceling out pairs of identical numbers.
      Example:
      5 ^ 5 equals 0.
      101 (binary representation of 5) ^ 101 (binary representation of 5) equals 000 (binary representation of 0).
      Commutative Property of XOR:
      The order in which you perform XOR operations does not affect the result.
      For any integers a and b, a ^ b is equal to b ^ a.
      The XOR operation is commutative.
      Example:
      3 ^ 5 is the same as 5 ^ 3.
      Associative Property of XOR:
      The grouping of XOR operations does not affect the result.
      For any integers a, b, and c, (a ^ b) ^ c is equal to a ^ (b ^ c).
      The XOR operation is associative.
      Example:
      (2 ^ 7) ^ 3 is the same as 2 ^ (7 ^ 3).
      These properties make XOR a powerful tool for finding unique elements in a set. In the context of finding a single number in an array where every other number appears twice, XORing all the numbers will cancel out pairs, leaving only the unique number.
      Consider an array [2, 2, 1, 4, 1]:
      2 ^ 2 ^ 1 ^ 4 ^ 1 is the same as (2 ^ 2) ^ (1 ^ 4 ^ 1).
      The pairs cancel out, and the result is the unique number: 0 ^ 4.
      The final result is 4, which is the number that appears only once in the array.

  • @balamuralikrishna_d
    @balamuralikrishna_d 5 місяців тому

    sometimes you make solution complicated and makes to quit coding

  • @cofing_challenge_1
    @cofing_challenge_1 2 роки тому

    0 xor 1 gives 1

  • @ghoshsuman9495
    @ghoshsuman9495 2 роки тому

    done

  • @ramahosman5904
    @ramahosman5904 2 роки тому

    This is giving me wrong answer. Anybody know why?

  • @venky3639
    @venky3639 2 роки тому

    First view first like 🤞

  • @evelynsummer4020
    @evelynsummer4020 2 роки тому

    can someone explain me from 4:11

  • @Prime_Code
    @Prime_Code 2 роки тому

    🔥🔥🔥🔥

  • @rabindrakumar949
    @rabindrakumar949 2 роки тому

    each value is index, now go to that index and make it -. if you see already the number is - then it is duplicate. if not - then it is unique.

    • @nameless2850
      @nameless2850 2 роки тому +3

      It wouldn't work assuming there are numbers which have bigger values then the length of the index

  • @i_code_daily
    @i_code_daily Рік тому

    let h = new Array(Math.abs(nums.length)).fill(0);
    if(nums.length == 1){
    return nums;
    }
    for(let i = 0 ; i < nums.length ; i++){
    h[Math.abs(nums[i])]++;
    }
    for(let i = 0 ; i < h.length ; i++){
    if(h[i] == 1){
    return i;
    }
    }
    Can anyone tell is my approach correct or not.
    And it does work for positive number but not negative 😅

  • @ngneerin
    @ngneerin 2 роки тому

    xor ^

  • @adiyogi-thefirstguru5144
    @adiyogi-thefirstguru5144 2 роки тому

    Please consider to make videos about DS and AL.. 🙏

    • @TheElementFive
      @TheElementFive 2 роки тому +1

      What do you think his channel is all about?

    • @girirajrdx7277
      @girirajrdx7277 2 роки тому +2

      He asked the viewers about it..and after taking viewers feedback via vote ..most of them voted against it.
      And y is that?...because it takes time for it and he have to dedicate energy and time just for it, which inturn drastically reduces frequency of neetcode videos
      Since DS and al is all over the youtube and with just some little more research you can find some wonderful yt channels teaching those.
      But for neetcode ..this is only channel we can blindly depend on!

  • @jackieli1724
    @jackieli1724 Рік тому

    😀😀😀

  • @cc-to2jn
    @cc-to2jn 2 роки тому

    lol love this problem,
    please never stop

  • @NN-uy6ik
    @NN-uy6ik 2 роки тому

    hi there, in case if someone doesn't understand so here will be another way:
    a = set{nums}
    return 2*sum(a) - sum(nums)
    this way is very easy to understand.

  • @AbTech114
    @AbTech114 2 роки тому

    Thanks!