Single Number - Leetcode 136 - Python

Поделиться
HTML-код
  • Опубликовано: 4 окт 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 года назад +128

    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 :)

  • @DanhWasHere
    @DanhWasHere 2 года назад +101

    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 2 месяца назад

      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 Месяц назад

      @@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 27 дней назад

      @@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!

  • @CostaKazistov
    @CostaKazistov 2 года назад +42

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

  • @jason1666
    @jason1666 2 года назад +104

    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 года назад +9

      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 месяца назад +2

      ​​@@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 6 месяцев назад

    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 7 месяцев назад

    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

  • @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.

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

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

  • @andriidanylov9453
    @andriidanylov9453 Год назад

    What a cool solution. Love it.👍

  • @kirillzlobin7135
    @kirillzlobin7135 Год назад +2

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

  • @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 года назад +1

      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

  • @ZechenGuo-h6t
    @ZechenGuo-h6t Год назад

    Awesome explanation!

  • @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.

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

    i would never ever think about it

  • @marekglowacki2607
    @marekglowacki2607 Год назад

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

  • @samlinus836
    @samlinus836 Год назад

    Brilliant explanation

  • @3zoabdullah333
    @3zoabdullah333 5 месяцев назад

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

  • @JonathanJoaquinQuirinoCarrasco
    @JonathanJoaquinQuirinoCarrasco 5 месяцев назад

    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

  • @souleymen971
    @souleymen971 Год назад

    Thank you very much

  • @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!

  • @sanooosai
    @sanooosai 2 месяца назад

    thank you

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

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

  • @jy76312
    @jy76312 3 месяца назад

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

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

    Thank you so much!

  • @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.

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

    Love you man!

  • @Alexthesurfer
    @Alexthesurfer 8 месяцев назад

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

    • @mehdisaffar
      @mehdisaffar 3 месяца назад

      return reduce(operator.xor, nums)

  • @BurhanAijaz
    @BurhanAijaz Год назад +1

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

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

    Would you consider doing fair indexes Leetcode 1882?

  • @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?

  • @natesgibson
    @natesgibson Год назад

    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

  • @edwardteach2
    @edwardteach2 4 месяца назад

    U a Single Number God

  • @NHCS-ShreyasChaudhary
    @NHCS-ShreyasChaudhary Год назад

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

  • @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

    • @bryanleow5024
      @bryanleow5024 Год назад

      @@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

  • @PradeepKumar-zt5nz
    @PradeepKumar-zt5nz 2 года назад

    Thanks

  • @zachlandes5718
    @zachlandes5718 5 месяцев назад

    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.

  • @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 Год назад

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

  • @sherwancaris5199
    @sherwancaris5199 Год назад

    Thanx

  • @balamuralikrishna_d
    @balamuralikrishna_d 4 месяца назад

    sometimes you make solution complicated and makes to quit coding

  • @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 года назад +7

      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"

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

    take an XOR of the elements.

  • @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 3 месяца назад +1

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

  • @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.

  • @manikamidha1692
    @manikamidha1692 2 года назад +1

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

  • @cc-to2jn
    @cc-to2jn 2 года назад

    lol love this problem,
    please never stop

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

    🔥🔥🔥🔥

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

    This is giving me wrong answer. Anybody know why?

  • @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

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

    can someone explain me from 4:11

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

    done

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

    0 xor 1 gives 1

  • @RobinHistoryMystery
    @RobinHistoryMystery 6 месяцев назад +1

    bit manipulation coding questions should be banned from coding interviews

  • @jackieli1724
    @jackieli1724 Год назад

    😀😀😀

  • @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!

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

    First view first like 🤞

  • @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.

  • @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 😅

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

    Thanks!