Single Number - Leetcode 136 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 15 ต.ค. 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 ปีที่แล้ว +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 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 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!

  • @CostaKazistov
    @CostaKazistov 2 ปีที่แล้ว +42

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

  • @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 หลายเดือนก่อน +3

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

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

  • @edwythefair5215
    @edwythefair5215 2 ปีที่แล้ว +8

    A difficult concept, thanks a lot!

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

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

  • @MonisKhan
    @MonisKhan 2 ปีที่แล้ว +15

    Thanks!

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

      Thank you so much!!

  • @deVamshi
    @deVamshi 2 ปีที่แล้ว +5

    Your explanation is so good

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

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

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

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

      Same here 😰

  • @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 5 หลายเดือนก่อน

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

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

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

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

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

  • @LoganLi-su5ju
    @LoganLi-su5ju ปีที่แล้ว +1

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

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

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

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

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

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

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

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

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

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

  • @NHCS-ShreyasChaudhary
    @NHCS-ShreyasChaudhary ปีที่แล้ว

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

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

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

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

      return reduce(operator.xor, nums)

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

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

    Would you consider doing fair indexes Leetcode 1882?

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

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

    Brilliant explanation

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

  • @ZechenGuo-h6t
    @ZechenGuo-h6t ปีที่แล้ว

    Awesome explanation!

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

    What a cool solution. Love it.👍

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

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

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

    i would never ever think about it

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

    Thank you very much

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

    thank you

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

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

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

    Thank you so much!

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

    U a Single Number God

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

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

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

  • @PradeepKumar-zt5nz
    @PradeepKumar-zt5nz 2 ปีที่แล้ว

    Thanks

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

    Love you man!

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

    Thanx

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

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

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

    This is giving me wrong answer. Anybody know why?

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

    take an XOR of the elements.

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

    sometimes you make solution complicated and makes to quit coding

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

    can someone explain me from 4:11

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

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

    done

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

    🔥🔥🔥🔥

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

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

    😀😀😀

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

    xor ^

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

  • @cc-to2jn
    @cc-to2jn 2 ปีที่แล้ว

    lol love this problem,
    please never stop

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

    Thanks!