Find All Duplicates in an Array - Leetcode 442 - Python

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

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

  • @ngneerin
    @ngneerin 8 หลายเดือนก่อน +72

    trick: whenever the question says numbers something about whole numbers until n, see if marking the index by making its value negative helps

    • @NguyenLe-nw2uj
      @NguyenLe-nw2uj 7 หลายเดือนก่อน

      thanks for the tip

  • @satyamjha68
    @satyamjha68 8 หลายเดือนก่อน +11

    Solved it in O(n) and constant space !! A beautiful problem . The O(n) approach is really elegant and smart.

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

    Quite a smart way to map the value itself to the respective index position (value - 1) in the nums array since the the array will always contain the numbers ranging from 1 to n.
    I couldn't figure it out without using a hash set. Thanks for the solution.

  • @leo38096
    @leo38096 8 หลายเดือนก่อน +3

    After reading cyclic sort technique, this solution make me feel more clear!

  • @aogimirou
    @aogimirou 8 หลายเดือนก่อน +1

    if you use a different property, you can do it in true O(1) space complexity by returning the input array after modification
    this involves adding n+1 to elements when visited and using %(n+1) to check further indexes
    u can then test for all values greater than 2(n+1) and change them to their index values (note the 1-indexing) and remove from list in O(1) for at worst n items, as relative order doesnt matter and thus removal can be done by swapping to end of array
    i think this approach adheres to the spirit of the question much better
    :)

  • @Maverick0813
    @Maverick0813 8 หลายเดือนก่อน +1

    This is epic. I can never come up with this idea on my own. Despite I use collections.Counter and list comprehension to reach to beat-85% runtime speed, your idea is still brilliant.

  • @ChristopherElwell
    @ChristopherElwell 8 หลายเดือนก่อน +1

    There’s actually a constant space and constant *time* solution. Basically you choose a random index and add that to the result array, then return immediately. The downside is that it has an accuracy complexity of P(1/N^2) avg case and P(0) worst case, however when it works it’s da best!

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

      Which dummy gave this soln a thumbs up ??

  • @fraserdab
    @fraserdab 8 หลายเดือนก่อน +2

    Index sort works as well!!

  • @varunpalsingh3822
    @varunpalsingh3822 8 หลายเดือนก่อน +2

    already solve it, with my own intuition of cycle sort but I feel its not very efficient although it was O(n) time, now I'm here to get more efficient solution

  • @mezuzza
    @mezuzza 8 หลายเดือนก่อน +1

    Alternative solution: you walk through the array,
    if a[i] - 1 = i, continue.
    If a[a[i] - 1] !=a[i], you swap them. Keep swapping until you either unravel the whole cycle, or you find a duplicate. If you find a duplicate, you can mark it and continue.
    Very similar, performance characteristics I believe.

    • @CrabGuyy
      @CrabGuyy 8 หลายเดือนก่อน +1

      i don't think that would work in O(n) time. Take for example the array 3 3 4 4

    • @swastiksanyal4249
      @swastiksanyal4249 7 หลายเดือนก่อน

      @@CrabGuyy no it is o(n).analyze it on your own

  • @asagiai4965
    @asagiai4965 8 หลายเดือนก่อน +1

    Nice unexpected solution.

  • @MehmetDemir-xi3yy
    @MehmetDemir-xi3yy 8 หลายเดือนก่อน

    Thanks for the video. Do you sometimes skip daily questions even if you didn't solve them? Because I don't remember exactly which dates (february or march) but I looked for the daily questions but I couldn't find them.

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

    ingenious as always

  • @art4eigen93
    @art4eigen93 8 หลายเดือนก่อน +1

    Cyclic sort is another solution

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

    Simple and wonderful as usual.

  • @thomaspsteven
    @thomaspsteven 8 หลายเดือนก่อน +2

    This is so clever

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

    generally speaking if ain't done in-place it's pretty much O(n) extra memory regardless. And can't think of solution less then O(nlogn) time which could swap out dupes somehow.

  • @atg878
    @atg878 8 หลายเดือนก่อน +1

    Brilliant❤❤❤❤

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

    Well when I saw the thumbnail of the video, I went straight to the leetcode and tried solving the problem myself . So thing that was confusing me was that we have to use constant extra space otherwise we could use a HashSet and store all the elements and then check if any element is present twice we push that to the result array or we could iterate through the array twice but that would be O(n2).
    So then I thought of the Dictionary(Key-Value) . So we can simply generate a frequency map using a for/foreach loop and keep track of the elements frequencies using a dictionary and when the frequency of an element equal 2 we push that to the result. So sine dictionary is not dependent on input array it's constance space and we are iterating through the array once so it's O(n).
    I'm getting better though xD.

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

      That's not constant space. This is just the hash set solution with minor modifications. The dictionary is totally dependent on the input array since you add all values in the input array to the dictionary.

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

      @@1vader You're correct that's O(n) space complexity since we're storing the frequencies of all elements of the input array. Shit

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

    Find the Duplicate Number Is very similar. It how I solved this question really fast

  • @kakaique2000
    @kakaique2000 7 หลายเดือนก่อน

    I’d solve this with the hare and tortoise algorithm, mutating the base array to keep a Constant space is hacky for me (and would not to be possible in functional langs), pretty straightforward solution tho

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

    Thank you!

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

    Hi nice solution does this logic work when we have a test case like this n =4 and nums = [3,3,3,3] this would return res =[3,3] and we would have duplicates in the result array so we may need to add a condition to check if that number is already present in the result list? Thanks in advance @neetcodeio

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

      Question says each element in input list occurs atmost twice, so your input is not possible

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

    This assumes mutability of the input data. You are still using O(n) space since you are "stealing" one bit from each array position to use as a flag and you need n of them.
    Its a clever solution to a problem that has a very badly specified question.

  • @pastori2672
    @pastori2672 8 หลายเดือนก่อน +2

    i think this is a mistake on their behalf but arent you making an extra array res that in the worst case gonna be of length O(n/2) which simplifies to O(n) ?, also here's a problem that is basically the same as this one for people who wanna solve it (yesterday's problem) : 287. Find the Duplicate Number

  • @il5083
    @il5083 8 หลายเดือนก่อน +6

    Should we assume we can use the input array as extra memory when we face this kind of problem in an interview? I thought this might be a bad practice in real world scenarios.

    • @NeetCodeIO
      @NeetCodeIO  8 หลายเดือนก่อน +2

      It's prob worth confirming with your interviewer before you start coding it. Fwiw it would be easy to revert the changes we made to the array if the interviewer prompted us to.

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

      Your coding interview is not supposed to reflect how you code in a normal environment, it’s meant to show your mentality. This problem in particular presents your ability to be resourceful

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

    in cpp
    class Solution {
    public:
    vector findDuplicates(vector& nums)
    {
    vector ans;
    for(int &it:nums)
    {
    int index=abs(it)-1;
    if(nums[index]

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

    Similar logic explained for 41.First Missing Positive
    Looks like this method could be applied to yesterday's
    287. Find the duplicate number also

    • @oneepicsaxguy6067
      @oneepicsaxguy6067 8 หลายเดือนก่อน +1

      True but yesterday's question specifically asked not to change the input array itself. So Floyd's Tortoise and Hare algorithm might be the only optimal solution based on yesterday's constraints

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

      @@oneepicsaxguy6067 oh! my bad

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

    when ever you see 1 to n or 0 to n use cyclic sort.

  • @vandananayak-y2o
    @vandananayak-y2o 4 หลายเดือนก่อน

    hi, for a input {8, 8, 7} it will give arrayoutofBound right?

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

      you can't have that input. for an array of length 3 only possible values are 1, 2, 3. read problem again

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

    can you do "126. Word Ladder II"? You have done 127, but this one is more specific and it can easily go to TLE. I cannot find a clear video solution for 127.

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

    I feel like you’ve done a video before where you use this trick of making values negative, can’t remember what the problem was though

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

    ur the goat

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

    Hey bro , i have a question to you , in today's market 40% jobs are on tool base d technologies like devops enginner , RPA developer , etccc . So Top product based companies work on these tools and sell these ools like microsodt developed power automate for RPA engineers . Sales force created muel soft for API developement . So it is good to go for working on these tool based techh orgo for DSA and work on creation of these technn. I request you to make a video these because , i see you have digging knowledge in Technology . Its a request .

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

    287. Find the Duplicate Number

  • @MyMojoSoDopeNights
    @MyMojoSoDopeNights 8 หลายเดือนก่อน +1

    Just sorted it and checked if nums[r] == nums[r-1] seemed to pass 🤷🏽‍♂️

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

      That is O(nlogn) time complexity

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

      lol thought about it in 1 minute coded it too. but thats not what matters.all that matters is O(n) TC.

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

      🤦🏿‍♂️ I thought sorting was log n not nlogn. I hate not being able to come up with solutions like these. I almost always have to see the solution. Was super excited to have come up with this. Back to the drawing board I guess

    • @priyam86f
      @priyam86f 8 หลายเดือนก่อน +1

      @@MyMojoSoDopeNights yeah, O(logn) is Binary Search. normal sorting algo internally is quick sort which is what makes it O(nlogn). Anyways this is the process you need to go through. If you give up during this journey you will not be a master. To be a master, or a chief grandmaster, you need to accept your defeat and show up everyday. And then there's some light at the end of the tunnel. Good luck! And happy coding bro. 🤓

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

    I 'am confused the problem says 'only constant extra space.' but we are using res as an array and appending to it

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

      you can ignore the space for creating res array, problems mean use only constant computation space (intermediate storage)

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

    Beast

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

    Would it also be O(1) if we remove duplicate from set after finding it?
    function findDuplicates(nums: number[]): number[] {
    const res = []
    const set = new Set()
    for (const num of nums) {
    if (!set.has(num)) {
    set.add(num)
    } else {
    set.delete(num)
    res.push(num)
    }
    }
    return res
    };

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

      No. In the worst case, there could be no duplicates and you add the whole array. Actually, this is basically never constant space. Basically the only time it would be is if all the numbers in the input are duplicates and the duplicates are always right next to each other.

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

    leetcode 448: Find All Numbers Disappeared in an Array

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

    i have a doubt
    if u are appending to res doesnt it make O(n) space?

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

      the problem statement states that return the array which is the result right

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

      @@kailashnaidu8268 hm

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

      Usually the answer (in this case the res array) isn’t counted towards extra space

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

      @@SegmentationFaultCoreDumped for every problem?

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

      In leetcode problems, pretty much. If the answer is an array of 5 elements, there’s nothing you can do to make it an array of 4 elements. By doing so you’d have the wrong answer. What you might be able to do is limit the extra space needed to achieve the answer. In this case he went for O(n) to O(1). But since the right answer is independent of the algorithm, it doesn’t help to include it when comparing algorithms. In the real world though, you would include it.

  • @Yeat23994
    @Yeat23994 8 หลายเดือนก่อน +1

    if we solve this using a hashmap the space complexity should still be O(1) because at the worst case we will be adding 26 characters to the hashmap.
    Right???

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

      Let me know if you get the answer and i still don't understand what is constant space if we are still using additional data structure

    • @1vader
      @1vader 8 หลายเดือนก่อน +1

      Where are you getting 26 characters from? You are adding all numbers in the array which is O(n).

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

    😱

  • @sharan10salian
    @sharan10salian 8 หลายเดือนก่อน +1

    I solved this without watching the video, NC pro