BRUTE FORCE DEVELOPER vs Optimal Toronto Engineer on Single Number, Leetcode 136

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ต.ค. 2024

ความคิดเห็น • 137

  • @GregHogg
    @GregHogg  5 หลายเดือนก่อน +18

    Master Data Structures & Algorithms For FREE at AlgoMap.io!

  • @shashwatsingh5129
    @shashwatsingh5129 5 หลายเดือนก่อน +322

    A constant space solution would be using the XOR operator. If you xor the entire elements present in the array, at the end you’ll be left with the number that appears just once.

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

      I think that's not very accurate, if the number of the repeated element was even it works but if odd it won't
      Am I right?

    • @saadal-tohamy2986
      @saadal-tohamy2986 5 หลายเดือนก่อน +42

      ​@@yousafshoiab1511
      that's right in general, but in that problem it says that every element appears twice

    • @gabrielbarrantes6946
      @gabrielbarrantes6946 5 หลายเดือนก่อน +2

      This one is nice for sure.

    • @qulinxao
      @qulinxao 5 หลายเดือนก่อน +3

      @@yousafshoiab1511 if all numbers tripled but some only doubled - you can find that number but not xoring(wich is %2) but summing each bit by modulo 3 so all bits %3 is

    • @shashwatnandan5083
      @shashwatnandan5083 5 หลายเดือนก่อน +2

      Evryone knows this solution 😂😂😂

  • @Krish_cse
    @Krish_cse 5 หลายเดือนก่อน +117

    result = nums[0]
    n=len(nums)
    for i in range(1,n):
    result^=nums[i]
    return result
    or simply use 1 line
    return reduce(operator.xor,nums)
    This XOR approach is the most efficient one

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

      Now THAT is a slick trick.

    • @hodayfa000h
      @hodayfa000h 5 หลายเดือนก่อน +1

      Xor is a pretty good solution

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

      Does that work in every possibility? Doesn't seem like it, but i didn't test it

    • @TamilarasuMK
      @TamilarasuMK 5 หลายเดือนก่อน +3

      ​@@hodayfa000h it will work in all the cases of integers. If it's a string, we can use stack approach as well.

    • @Krish_cse
      @Krish_cse 5 หลายเดือนก่อน +2

      @@TamilarasuMK the question says an array of integers. It will work on all test cases.

  • @crazymemes4080
    @crazymemes4080 5 หลายเดือนก่อน +107

    BRO open your eyes 👀 question states constant space :) performance XOR and do it

    • @400elochess
      @400elochess 4 หลายเดือนก่อน +4

      Constant EXTRA Space
      the memory you used to solve, isnt dependant on the input variable.

    • @jffrysith4365
      @jffrysith4365 4 หลายเดือนก่อน +12

      @@400elochess but it is isn't it. because the counter is a hashmap which will have the number of different numbers in nums in it. which is O(n) space isn't it?

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

      @@jffrysith4365 yeah, for constant space, no for loops

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

      ​@@jffrysith4365 yes it is, too many don't understand the org aspects

  • @ZenMachina16
    @ZenMachina16 4 หลายเดือนก่อน +7

    When dealing with a problem where every element in an array appears twice except for one unique element, a very effective approach is to use the XOR operation. This is because XOR has the property where a ^ a = 0 and a ^ 0 = a. This means that any number XORed with itself results in zero, and any number XORed with zero results in the number itself.

  • @armandomendivil1117
    @armandomendivil1117 5 หลายเดือนก่อน +8

    You can use XOR to solve it in constant space and that’s because if we use XOR for the same number the result is 0 and if we use XOR any number with 0 the result es the number 1 XOR 1 = 0, 2 XOR 0 = 2

  • @FrezoreR
    @FrezoreR 5 หลายเดือนก่อน +50

    You missed the constant space part in your solution.

    • @fahimalizain7598
      @fahimalizain7598 5 หลายเดือนก่อน +1

      Number of elements in the hasmap is constant (0-9)

    • @FrezoreR
      @FrezoreR 5 หลายเดือนก่อน +7

      @@fahimalizain7598 That's not technically constant as it depends on the input.

    • @DavideCanton
      @DavideCanton 5 หลายเดือนก่อน +3

      ​@@fahimalizain7598 It isn't. It's linear, exactly (n-1)/2

    • @jffrysith4365
      @jffrysith4365 4 หลายเดือนก่อน +2

      @@fahimalizain7598 it's not 0-9, it's 1-3E4. So in the spirit of the problem it's unbounded.

  • @jfs5184
    @jfs5184 5 หลายเดือนก่อน +6

    reduce(lambda acc, n: acc ^ n, nums)

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

      functools.reduce(operator.xor, nums)
      More readable I think 😊

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

    First of obv XOR.
    Second, the task description does not fit the function signature. In the description the numbers are given as array, while in the function typing, it's passed as list, what is not the same in Python. And especially for low level operations like XORing, it makes a huge difference in performance and possible speed operations.
    I'd assume that np.bitwise_xor(nums) should be very close to C/Fortran speed if nums are an array, while for the same thing with a list, the conversion first to a compact memory structure that numpy would do, might be slower than just a for loop xoring it or similar (and probably 2 magnitudes slower than with an array).
    In case you wonder, a list in CPython is basically a pointer to an array of pointers to arbitrary objects. It's a flexible structure, but very space- and cache inefficient. An array in python is pretty much the same as in C (or detail, it's a struct with an array, plus some slight overhead with counting references to it for garbage collection and typing/array size information, but any operation on it will just similar performant as safe C/Rust/Fortran code, for the latter at least if you use numpy).

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

    i'm at first year of software engineering so i ask people that probably know more than me.
    My first thought was sorting the array, and every two numbers are going to be equal so if we could cast an "if x[i]≠x[i+1] return x[i]; i++;"
    Seems like a linear function to me, could take max half of the array length to go through everything.
    I dont know how hashmaps work in the hardware but i assume counter also just loops through the whole array.

    • @Energy0120
      @Energy0120 4 หลายเดือนก่อน +1

      ok nvm i took for granted the sorting algorithm, i take it back

  • @IOSALive
    @IOSALive 5 หลายเดือนก่อน +4

    Greg Hogg, This is amazing! I can't stop smiling!

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

      Hahah why's that

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

      Posting suboptimal solution to increase engagement 😂

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

    val list = listOf(1, 5, 4, 3, 1, 4, 5, 2, 3)
    val result = list.reduce { a, b -> a.xor(b) }

  • @ziggywiggys
    @ziggywiggys 5 หลายเดือนก่อน +1

    Why not take XOR of all elements ?
    Fast and Space Optimized

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

    You can just xor all the number in the array and your result is the number wich appear only one time .
    actually if you xor a number even time your result will be ZERO(for example 3 ^ 3 ^ 3 ^ 3=0) and if you xor a number odd time your result will be your firs number( for example 3 ^ 3 ^ 3 ^ 3 ^ 3=3).

  • @RS-fz4ps
    @RS-fz4ps 5 หลายเดือนก่อน

    If it is only integers, find min and max, iterate over the range of min to max searching for each occurrence with a minimum appearance of twice, the first one that you find once is the answer. No space of the counter required, albeit maybe not optimal runtime.

    • @lukares9468
      @lukares9468 5 หลายเดือนก่อน +1

      [1,1, 99999, 100000, 100000]
      Your program will iterate from 1 99,999 before finding the solution.

  • @Leehagoodjames
    @Leehagoodjames 5 หลายเดือนก่อน +4

    This uses linear extra space

  • @ezion
    @ezion 4 หลายเดือนก่อน +1

    You make it look so easy

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

      It's a planned, recorded video. This doesn't show the hours I've put in to learning this :)

  • @kumarashutosh-p3n
    @kumarashutosh-p3n 5 หลายเดือนก่อน

    CAN ALSO SOLVE VIA HASHING HAVING ARRAY OF N+1 SIZE AND PUTTING FREQUENCY TO THE INDEX.

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

      thats not constant space as the longer the array the bigger the hashmap you need

    • @kumarashutosh-p3n
      @kumarashutosh-p3n 5 หลายเดือนก่อน

      @@amanthinks374 who said i was talking about constant space. that's a way i offered

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

    Found = set()
    For x in nums:
    If x in found: found.remove(x)
    Else: found.add(x)
    Return found

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

    make a freq array - store each num in their index.
    for each element in nums, return i if arr[i] ==1

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

      You need to find max first, also very space-consuming, use set or dict

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

      @@phusicus_404 max is in the constraints, you make the size the same as that. so it’s O(n) time and O(1) space.

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

    It can be easily done as a one liner using list comprehension

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

    Still Not a super optimal one because it is still using an extra space!!
    You can go with the XOR operator which will eventually cut down the auxiliary space!!

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

    Is every single "Veteran Dev" solution to throw said thing into a hash map?

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

      It's pretty common yes hahaha

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

    Ontario has the best developers, gems in the small towns that all end up in Toronto or Montreal.

  • @davea136
    @davea136 5 หลายเดือนก่อน +2

    Python3 Use Set.
    my_set = {}
    Add each number to the set when first visited, remove it when visited a second time. The remaining member(s) of the set only appeared once.
    Answer will be:
    list(my_set).
    Can anyone think of anything wrong with this solution? Thanks.

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

      Just return number if it's is present in set
      If single numbers would be multiple then yes

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

      A set is linear space. In worst case the set will contain n/2 elements (all the duplicates are in the second half of the areay), and the problem states constant space.

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

      @@cbtheodor "constant extra space"
      Which means the set is fine, because it will never have more than the space of the list plus a bit for the keys. It isn't my fault python won't let me malloc that space from the start for the set. (But python will malloc plenty pof space, it isn't dumb enough to realloc constantly).
      And yes, I know the "use XOR" trick. But if a question is this simple I assume there will be a follow-on question to make it harder. The "assume everything but one entry is doubled" is extremely fragile base condition.

  • @pushkardev3090
    @pushkardev3090 4 หลายเดือนก่อน +1

    Just use XOR.

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

    Simplest is using xor

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

    Using the xor will the optimal one your code is just an better method

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

    Shouldnt the final condition be that
    If (map.get(i) != 2)
    Return result as i
    Since the question only mentions that except one all will be occuring exactly twice. So couldnt a number occur 3 times too based on question & not just once?

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

    Scala one-liner:
    def singleNumber(nums: Array[Int]): Int = nums.foldLeft(0)(_ ^ _)

  • @naveenchhipa7524
    @naveenchhipa7524 5 หลายเดือนก่อน +1

    Use xor

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

    I would have just done this using a set... I guess the hasmap approach is faster?
    def find_single_element(arr):
    seen = set()
    for num in arr:
    if num in seen:
    seen.remove(num)
    else:
    seen.add(num)
    return seen.pop()

  • @ashreekar4896
    @ashreekar4896 5 หลายเดือนก่อน +2

    Int ans=0;
    For i-0 to nums.size-1
    ans=nums(I)^ans;
    Return ans;

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

    Why not just use a stack?

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

    I know till the hashmap part, but keep forgetting the Counter function and making a loop instead

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

      It's not just function, more like a constructor

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

    What if we use .count() ?

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

    Constant extra space... but uses a hash map of n elements...

  • @polycrystallinecandy
    @polycrystallinecandy 5 หลายเดือนก่อน +13

    Conveniently ignore "use only constant extra space"
    Actual solution is x = reduce(operator.xor, nums)
    Idk if this guy deliberately posts bad solutions/advice to drive engagement. In which case, well done sir, I've played right into your hands.

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

      He has said he trained for data science, so probably never went through basics in machine code or assembly and never saw _Programming Pearls_ or _Hacker's Delight_. And it is good to see different ways to solve the same problem, so I offered a different take too, using python's set. Same thing, different idiom. So cut him a break. I like his channel. Thanks for reading this far!

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

      @@davea136 using a set has the same flaw, O(n) space usage. Btw I've never read those books either. Many people post incorrect things so they get more comments, which makes it more likely their videos will go viral

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

    if you didn't know about Counter() like me... you could solve like this:
    class Solution(object):
    def singleNumber(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    foundNumber = 0
    nums.sort()


    for i in range(len(nums)):
    if len(nums)

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

    what is the site he's using to test his solution?

    • @GregHogg
      @GregHogg  5 หลายเดือนก่อน +1

      Leetcode

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

    return min(Counter(nums).items(),key = lambda x : x[1])[0]

  • @ndchunter5516
    @ndchunter5516 5 หลายเดือนก่อน +1

    hm the size of the hashmap is still n/2+1 if i see that right...depending on how it performs, how about sorting the array and go 2 steps at a time and check of the i==i+1?

    • @masunori
      @masunori 5 หลายเดือนก่อน +1

      Sorting itself is O(n log n)

  • @HR-pz7ts
    @HR-pz7ts 5 หลายเดือนก่อน +1

    What about xor?

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

      nobody uses it in real world

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

    Cold in Canada eh?

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

    Is bit operation not available in python?

  • @AnshuSingh-ek4zu
    @AnshuSingh-ek4zu 5 หลายเดือนก่อน

    I think bitwise XOR is more optimal

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

    Would a set() approach work here as well?

    • @alxjones
      @alxjones 4 หลายเดือนก่อน +1

      Yep, add to a set if it's not in it, remove from a set if it is. The resulting set will be a singleton containing the solution.

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

      @@alxjones Wonderful! Thank you so much for responding!

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

    Meanwhile XOR operator: 🗿🚀

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

    Binary search left the chat

  • @GoodBoy-my8mv
    @GoodBoy-my8mv 4 หลายเดือนก่อน

    You have not read the follow up 😊

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

      Lol

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

    XOR to the rescue!!!
    class Solution {
    public:
    int singleNumber(vector& nums) {
    int result = 0;
    for(int i = 0; i< nums.size(); i++)
    {
    result ^= nums[i];
    }
    return result;
    }
    };

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

    I really like your videos.

    • @GregHogg
      @GregHogg  4 หลายเดือนก่อน +1

      Thank you, that means a lot :)

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

    Better use an hashset

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

    If you’re gonna make these solutions seem trivial with these 1 minute shorts, at least come up with the right solution per the problem statement. Hash map is not constant space.

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

    My FOMO made me think Toronto is a new framework 🤦‍♂️

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

    Nice solution

  • @Funpage1940
    @Funpage1940 5 หลายเดือนก่อน +1

    Xor

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

    Learnt this from hackerrank💀

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

    Xor bro xor

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

      Yes!

  • @progressiveaccount3270
    @progressiveaccount3270 5 หลายเดือนก่อน +2

    xor

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

    You usually get it right but not this time.

  • @HKS-Digital
    @HKS-Digital 4 หลายเดือนก่อน

    So basically the solution to everything is a hash map 😂

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

    Xor would be better 😅

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

    analog electronisc say that even idiot can count to 1, so set is enough.

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

    One line solution (but not optimized thought) for a given list called l:
    {l.count(i): i for i in l}[1]

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

    Hashmap is linear in space lol

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

    When wannabe developers make videos on TH-cam. this is a constant space question using XOR operator.

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

      When wannabe idiots write comments

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

    Let me give you a much better solution
    Just do the xor operation of all element and you will get your answer ❤😂

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

    Unfortunately, the video deserves a dislike because the part about constant extra space was completely ignored, and it made the second solution misleading and useless.

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

    Bit xor of

  • @XX-vu5jo
    @XX-vu5jo 5 หลายเดือนก่อน

    Huh? Just XOR! What’s wrong with this channel? People watching this and learning bad coding. 💀💀

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

      If you disagree with this channel then you're a bad programmer

    • @XX-vu5jo
      @XX-vu5jo 5 หลายเดือนก่อน

      @@paulblart7378 huh? you want to compete with me? Bruh, I can walk the talk. If you patronize this channel, you're a bad and garbage programmer.

  • @tjscorp
    @tjscorp 5 หลายเดือนก่อน +1

    Failed! O(n) space!!

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

    let tab=[1,1,2,3,3,4,4]
    let value=0
    tab.forEach(val=>{
    tab.filter(val1=>val1===val).length == 1 ? value = val : null
    })
    console.log(value) // 2

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

    Constant space wtf

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

    const singleNumber = list => {
    let checked = new Set(),
    singles = new Set();
    list.forEach(value =>
    checked.has(value)
    ? singles.delete(value)
    : (checked.add(value), singles.add(value)));
    return singles.size === 1 ? [...singles].at(0) : 'not single number';
    }

  • @pranavpranjal2717
    @pranavpranjal2717 5 หลายเดือนก่อน +3

    Use xor

  • @9-1939
    @9-1939 5 หลายเดือนก่อน +2

    Xor