Contiguous array | Leetcode

Sdílet
Vložit
  • čas přidán 12. 04. 2020
  • This video explains a very important programming interview problem which is to find the count of all contiguous array will equal number of zeroes and ones. This problem is one the most important problem type and has also repeated in google kickstart 2020 round C question 3 which is perfect subarray. I have explained the intuition for solving this problem and then showed a solution using map. At the end of the video, i have explained the CODE for the algorithm and as usual, the CODE LINK is given below. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    CODE LINK: gist.github.com/SuryaPratapK/...

Komentáře • 177

  • @shivanggupta5421
    @shivanggupta5421 Před 4 lety +27

    I was stuck on this for a while and saw 2 more videos before this. But you explained it really well. Thanks

  • @anand_dudi
    @anand_dudi Před 4 měsíci +2

    this is the best channel for finding best algorithm to problem. not even @neetcode can explain easy and efficient algorithm which this channel does

  • @juuzousuzuya69
    @juuzousuzuya69 Před měsícem

    I was stuck on this but you explained it well. Im just thinking no way I would know this solution unless Ive seen it :D

  • @aparnamane1164
    @aparnamane1164 Před 4 lety +4

    I really love your videos. The explanation is quite crisp and clear. Keep posting. Thankyou.

  • @gourabbanerjee4152
    @gourabbanerjee4152 Před 4 lety +6

    The best explanation for this problem! Good Job!

  • @aadil4236
    @aadil4236 Před 4 měsíci

    Thank you mate. for the edge case when we get zero as current sum, we can just add "0: -1" in the hashmap in the start and don't have to worry about it in the code to check that edge case.

  • @bisheshwardevsharma3243
    @bisheshwardevsharma3243 Před 13 dny +1

    Thank you. It was a good explanation

  • @aswathsrimarir2501
    @aswathsrimarir2501 Před 4 lety +2

    You are doing a good job...following all your videos. ..keep uploading.

  • @halfaddercircuit
    @halfaddercircuit Před 2 lety

    Your approach is great. I used map as well but very nasty. Great explanation.

  • @goutamkundu6392
    @goutamkundu6392 Před 3 lety +1

    Your channel is gold. Just 1 small optimisation can be not using the map but using an array to contain the sum. We can take an array of length 2*n+1 where n=length of given nums array. We can add n to each sum i.e., we can initialise our sum variable with n rather than 0. Next all the things are same. The logic is quite obvious. If the given nums array contains all 1's, then max sum possible is n and we are adding n to it, so total n+n=2n. That's why taking an array for hash of length 2*n+1. If the given nums array contains all 0's, then sum will become -n+n=0. Hence, we can accomodate all values in our 2*n+1 hash array.

  • @qilinzhang6958
    @qilinzhang6958 Před 4 lety +4

    Thanks very much, I completely understand your explanation, great job.

  • @najimali32
    @najimali32 Před 4 lety +6

    This question is good & you explain it the nice way. I also have a similar approach, but your code is more compact.

  • @pranayraj7938
    @pranayraj7938 Před 4 lety +4

    Nice Explanation !!...I was waiting for ur video.

  • @PremPal-uy4nm
    @PremPal-uy4nm Před rokem +1

    For the people who heard "Contiguous Subarray" first time.
    Contiguous Subarray means any part of array where no elements are skipped. [1,2,3,4,5] has [3,4,5] as contiguous subarray but [1,4,5] is not Contiguous Subarray. We can think kind of continuous subarray.

  • @chrisjurgens8043
    @chrisjurgens8043 Před rokem

    Great explanation, helped me solve for sure!

  • @ryanchen467
    @ryanchen467 Před 2 lety

    The is the best explanation I've seen

  • @Giri14_18
    @Giri14_18 Před 4 měsíci

    Great explanation ........Thank you sir

  • @lemax2980
    @lemax2980 Před 4 lety +7

    Ur channel is a gem bro.I feel lucky to be a subscriber😅 .All the best bro..🙌🙌

  • @meet2637
    @meet2637 Před 3 lety +1

    This channel is gold.

  • @venkateshthirunagiri85
    @venkateshthirunagiri85 Před 4 lety +8

    how will you get this type of IDEAS man? like replace 0 with -1 then compute the problem........this is mind-blowing. love your channel dude and thanks for making videos " SURYA PRATAP KAHAR " :)

    • @techdose4u
      @techdose4u  Před 4 lety +8

      Actually I had seen such trickery in some other problems. So whatever is seen, quickly comes into mind 😅

  • @saurabh.gupta22
    @saurabh.gupta22 Před 4 měsíci

    Great Explanation ❤

  • @abhishekkumarjhariya1340
    @abhishekkumarjhariya1340 Před 2 lety +2

    Great explanation as always.

  • @ganeshjaggineni4097
    @ganeshjaggineni4097 Před měsícem

    NICE SUPER EXCELLENT MOTIVATED

  • @subham-raj
    @subham-raj Před 4 lety +3

    *Closer to prefix sums*

  • @kushgupta1187
    @kushgupta1187 Před 4 lety

    Very well explained

  • @akhilesh59
    @akhilesh59 Před 2 lety +2

    Thanks for the explanation :)

  • @mohamedhesham6008
    @mohamedhesham6008 Před rokem

    That's really amazing explanation

  • @akshayaamar9825
    @akshayaamar9825 Před 2 lety +1

    Very well explained. Thank you.

  • @ajaywadhwa3398
    @ajaywadhwa3398 Před 3 lety +1

    Really Impressive. Helped a lot !!

  • @kumarswamy3554
    @kumarswamy3554 Před 3 lety +1

    very clear explanation. Thank you so much.

  • @priyamani4349
    @priyamani4349 Před 4 lety +2

    Great work.

  • @suryajanardhan
    @suryajanardhan Před 4 měsíci

    very good explanation

  • @dhanashreegodase4445
    @dhanashreegodase4445 Před 2 lety +1

    Keep posting. Thankyou.

  • @ishmeetbindra5428
    @ishmeetbindra5428 Před 4 lety +1

    Nicely Explained!

  • @praveenchouhan6388
    @praveenchouhan6388 Před 4 lety +2

    brilliant work!!!!!!!!!!!!!!!!!!!!

  • @sumitSharma-ed5mi
    @sumitSharma-ed5mi Před 2 lety +1

    Very good explanation and its very helpful

  • @ahmedfouzan
    @ahmedfouzan Před 2 lety +1

    Thanks for the clear explanation

  • @sujiths9199
    @sujiths9199 Před 2 lety

    I really appreciate your thought process

  • @Learner010
    @Learner010 Před 4 lety +1

    the best explanation!!

  • @tanishqaggarwal1197
    @tanishqaggarwal1197 Před rokem

    Nice approach

  • @debashisdas6593
    @debashisdas6593 Před 4 lety +1

    Nice explanation !!!

  • @aviligondagowtham1153
    @aviligondagowtham1153 Před 4 lety +2

    Sir,could u pls explain the c code based on whatever u will say the problem so that it will be better .. u r the best tutor I never seen really

    • @techdose4u
      @techdose4u  Před 4 lety

      If you are doing coding in C then will recommend you to switch to C++ as soon as you can. It will be a cakewalk to switch. C doesn't have standard libraries. You will be at ease. Believe me.

    • @aviligondagowtham1153
      @aviligondagowtham1153 Před 4 lety +1

      As per our placement the companies will give more preference to c languge so tht I'm learning

    • @techdose4u
      @techdose4u  Před 4 lety +2

      I heard this the first time. Can you name some companies who prefer C over CPP?

    • @akshitajha1209
      @akshitajha1209 Před 2 lety

      Yes plzz switch to C, it's involves tedious work even for basic things, change it ASAP, I also made this mistake so highly recommend u! Well this comment is 1 year ago
      M sorry but to whomsoever it may concern!

  • @sarvesh6785
    @sarvesh6785 Před 2 lety +1

    Python3 code:
    class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
    dic = {}
    sum = count = 0

    for i in range(len(nums)):
    sum += 1 if nums[i] == 1 else -1

    if sum == 0:
    count = max(count,i + 1)
    elif(sum in dic):
    count = max(count,i - dic[sum])
    else:
    dic[sum] = i
    return count

  • @ganakkathuria4893
    @ganakkathuria4893 Před 2 lety +1

    Nice explanation

  • @Yash-uk8ib
    @Yash-uk8ib Před 4 lety +4

    sir, i appreciate ur method. It's nice. Maybe, i have another approach, plzz tell me whether it works or not. If not, then plz explain why?
    APPROACH: compute the count of zeroes and ones from the array and find min(count_of_zero, count_of_one)*2. This expression will give you maximum length of subarray. If any of these counts is/are 0, then no subarray is possible which meets the given criteria.

    • @techdose4u
      @techdose4u  Před 4 lety +7

      I had thought this as my first idea and you did too 😅 This won't work because counting is not taking contiguous element property into consideration. It may skip some elements in between and say the answer. This can work for subsequence where you can skip any element but this won't work for subarray. Take the example of 0 1 1 1 0. You method will give 4 but answer is only 2. I hope you got it :)

    • @Yash-uk8ib
      @Yash-uk8ib Před 4 lety +2

      @@techdose4u ohhkk... i got it

    • @techdose4u
      @techdose4u  Před 4 lety

      :)

    • @stankafan6688
      @stankafan6688 Před 4 lety +2

      hahaha bhaiya i too thought same for the first time 😅

    • @soumavabanerjee5925
      @soumavabanerjee5925 Před 2 lety

      I tried this one too at first and got WA XD

  • @jaydeepmahajan6598
    @jaydeepmahajan6598 Před 4 lety +4

    I have seen this video last month still i need to watch this video agin , i am just getting demotivated for this , why ideas are not coming in my mind ?

    • @techdose4u
      @techdose4u  Před 4 lety +1

      You should fully understand a problem and then solve similar problems yourself in order to remeber it.

  • @syed7996
    @syed7996 Před 4 lety +1

    Thanks for the video, but how you decided to use hash map? How do you get that intuition. why not variables?. Please make a series of videos on how to get that intuition. It requires practice as suggested by many but still curious to know

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Will make it in near future for sure :)

  • @amanvijayvargiya3468
    @amanvijayvargiya3468 Před 4 lety +1

    thank you so much ..

  • @muskanmangal8938
    @muskanmangal8938 Před 4 lety +1

    It helped!

  • @yashshreeshinde4394
    @yashshreeshinde4394 Před 3 lety +1

    Thank you!!!!

  • @audioplatform6299
    @audioplatform6299 Před 3 lety +2

    All good... very clear explanation as always in your channel...
    But, is it fair for the companies to expect someone to think of a solution for this kind of hard problem and code it in 45 minutes?

    • @techdose4u
      @techdose4u  Před 3 lety

      Generally you won't be asked hard problems.

  • @AnkitRaj-jn8ew
    @AnkitRaj-jn8ew Před 4 lety +1

    Instead of having the condition sum == 0, we can initialize the map mymap[0] = -1 and when we encounter 0, i+1 will be added to longest_subarray.

    • @techdose4u
      @techdose4u  Před 4 lety

      We could have done map[0] = 1 and then iterated.

    • @AnkitRaj-jn8ew
      @AnkitRaj-jn8ew Před 4 lety +1

      @@techdose4u shouldn't it be map[0] = -1 and not map[0] = 1 because this way, when sum is 0, it will be i - (-1) = i + 1

    • @techdose4u
      @techdose4u  Před 4 lety

      The idea is to add. If you take minus sign then take -1. This time around I solved with 1 😅 It all depends on how you manipulate the calculation.

    • @AnkitRaj-jn8ew
      @AnkitRaj-jn8ew Před 4 lety

      True, I said -1 in agreement to the equation in the video "longest_subarray = i - mymap[sum]" where using +1 could make it wrong.

  • @ryan.aquino
    @ryan.aquino Před 4 lety

    python
    data = nums
    hm = {}
    res = 0
    ctr = 0
    for i in range(len(data)):
    if data[i] == 0:
    ctr -= 1
    else:
    ctr += 1

    if ctr == 0 and i+1 > res:
    res = i+1
    if ctr not in hm:
    hm[ctr] = i
    else:
    val = i-hm[ctr]
    if val > res:
    res = val
    return res

  • @rahulchaubey8988
    @rahulchaubey8988 Před 4 lety +1

    👌👌👌👌👌👌

  • @vinoltauro9160
    @vinoltauro9160 Před 3 lety

    can we use the sliding window technique ?

  • @ssaha7714
    @ssaha7714 Před 2 lety

    I am just wondering what is wrong if we take a loop, 2 variables and then the lower count multiplied by 2 is the answer. Am I missing something from the question.
    private int maxLength(int[] arr){
    int zeroCount =0;
    int oneCount =0;
    for(int I=0;I

  • @nidhisingh25_
    @nidhisingh25_ Před 4 lety +2

    Had a doubt!! What if the array starts with 0 this code will not work then. For example : [0,0,1,0,1,1,1,1,0]. Can you please explain? If sum becomes -1 or -2, then it will be stored in map which might be wrong I guess? Correct me if I am wrong...

    • @techdose4u
      @techdose4u  Před 4 lety

      I guess u r thinking how can we have negative index, right? Well, we are not actually accesing by index but we are storing index. We are storing both key and value as pair in map. Key can have any value. So don't worry, it will work.

  • @anjalisinha3377
    @anjalisinha3377 Před 3 lety +1

    Code in Java -- @TechDose
    class Solution {
    public int findMaxLength(int[] nums) {
    HashMap hm = new HashMap();
    int sum =0;
    int max=0;
    int temp=0;
    for (int i=0; i

  • @shubhamgarg7198
    @shubhamgarg7198 Před 4 lety +2

    How you build your such good concepts?? To produce optimal solutions

    • @techdose4u
      @techdose4u  Před 4 lety +2

      First I think atleast one solution and try solving. If it works then I try optimizing different steps for that problem. This method works for me.

  • @locusoflearning
    @locusoflearning Před 3 lety +1

    Thanku sir.

  • @mayankchauhan6680
    @mayankchauhan6680 Před 3 lety +1

    how does a solution strike the mind? Is it just about intuition who just a few smart people happen to have, or you get to learn a particular pattern over a long period of time by solving problems over and over?

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Your last guess is right. Everyone is smart in common matters but once we talk about a specific skill then you need to train your brain over a period of time.

  • @virinchimsk83
    @virinchimsk83 Před 4 lety +1

    Sir I have a doubt!.. I am using python for ds. Can I use inbuilt function like dict() or keys() in coding interviews for hashing??...will this works(I.e runtime error may comes)..not only this there are many inbuilt function in python. Is it a good practice to use them.

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Avoid inbuilt functions but use basic ones. Dict and keys are fine. Mostly you will be good. But if are required to implement an algo then don't just use inbuilt fn to solve it. Like you are asked to calculate lower bound of a number then use binary search instead of lower bound built in fn. If you are asked a larger problem to solve where you need to find lower bound then you can use built in fn.

    • @virinchimsk83
      @virinchimsk83 Před 4 lety

      Thnks sir😃

  • @stankafan6688
    @stankafan6688 Před 4 lety

    bhaiya can't we use stack.
    int findMaxLength(vector& nums) {
    int s,i,count=0,max=0;
    s=nums.size();
    stackst;
    st.push(nums[0]);
    for(i=1;i

  • @rahulsaini202
    @rahulsaini202 Před 3 lety +1

    @TECH DOSE To check element is present in map or not. Sometimes we write mymap[sum] and sometime we write mymap.find(sum)!= mymap.end()... Please can you explain this? Thanks.

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Mymap[sum] will return value stored at key Sum (provided the entry is already present in map). Find is used to check if there is any valid entry present with the given key Sum. So, 2nd one can be used to check. 1st one is used to retrieve value when you know it's present else you want to initialise a new value.

    • @rahulsaini202
      @rahulsaini202 Před 3 lety

      @@techdose4u Thanks for the response.

  • @najimali32
    @najimali32 Před 4 lety

    I think when sum is zero is not handle correctly , i m getting wrong ans,
    Python sol:
    class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
    n = len(nums)

    sum ,c_arr = 0,0
    //hash map
    d = dict()
    d[0]=-1
    for i in range(n):
    if nums[i]:
    sum+=1
    else:
    sum-=1
    // checking if the key is present in hashmap
    if sum in d:
    c_arr = max(c_arr,i-d[sum])
    else:
    d[sum]= i
    return c_arr

  • @damodaranm3044
    @damodaranm3044 Před 4 lety +1

    bro . you have done a excepional job .youre better than nick white kelvin naugton . pls dont go fast while u teach . thanks

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Thanks bro :)

    • @damodaranm3044
      @damodaranm3044 Před 4 lety

      @@techdose4u go slow while u teach bro . because we are like small kids in problem solving . and the way u teach is amazing keep it up i appreciate it

  • @akshitajha1209
    @akshitajha1209 Před 2 lety +1

    I m loving the explanation but have a sense of guilt too that I was unable to solve it on my own. I tried and know about basic prefix sum but still loving this solution which I was unable to think of. What shall do? Is it fine?

    • @techdose4u
      @techdose4u  Před 2 lety +1

      It's fine. Just don't watch the code implementation and try yourself. If you can't do then see it :)

  • @baxtables
    @baxtables Před 3 lety

    is it a dp problem?

  • @parekshamanchanda8083
    @parekshamanchanda8083 Před 4 lety +1

    Can be done with stack as well

  • @subhadippatra7930
    @subhadippatra7930 Před 4 lety +1

    Will you keep all the videos free in future or you will move to a paid platform ?

    • @techdose4u
      @techdose4u  Před 4 lety

      Problems will be free. I will include donations in near future. If it goes well then everything will be free forever.

  • @ankitchaturvedi2941
    @ankitchaturvedi2941 Před rokem

    can we solve it without map

  • @akashmittal7795
    @akashmittal7795 Před 4 lety +3

    can you explain what this line means?
    sum += nums[i]==0?-1:1;

    • @techdose4u
      @techdose4u  Před 4 lety +3

      It is Ternary operator. It means if mums[i] == 0 then select value -1 else select 1. After selection, we have given a shorthand addition operator to add the result to sum. So sum will be added by either -1 or 1 depending on the check I performed. I hope you got it :) It is easier than writting bunch of lines of if else statement to do it.

    • @mayankchauhan6680
      @mayankchauhan6680 Před 3 lety

      if(nums[i] == 0) {
      sum = sum-1;
      } else sum = sum+1

  • @sahilanand30
    @sahilanand30 Před 2 lety +1

    You just explained the solution
    But there is no intuition

  • @muskaangupta4920
    @muskaangupta4920 Před 4 lety +1

    Why did you compare mymap.find(sum) with mymap.end()?
    Can't be simply
    If(mymap.find(sum))

    • @techdose4u
      @techdose4u  Před 4 lety

      It is given to see if on searching the element you reached end of map or not. If you did, that means the element is not present. You can use map.count(sum)

    • @muskaangupta4920
      @muskaangupta4920 Před 4 lety +1

      Okay. Got it!!

    • @techdose4u
      @techdose4u  Před 4 lety

      👍

  • @DEEPAKYADAV-vb2ee
    @DEEPAKYADAV-vb2ee Před 4 lety +2

    Would you help me.
    How to find maximum GCD of the subarray.
    For eg. arr = { 2, 3,4,4,4}
    Here max subarray as welll as max GCD is ={4,4,4}.
    Help me what will be your efficient approach.
    @Tech Dose

    • @techdose4u
      @techdose4u  Před 4 lety +1

      What can be the size of subarray?

    • @DEEPAKYADAV-vb2ee
      @DEEPAKYADAV-vb2ee Před 4 lety

      @@techdose4u all the size of subarray >=2 of the given array

    • @DEEPAKYADAV-vb2ee
      @DEEPAKYADAV-vb2ee Před 4 lety

      @@techdose4u it is just same as the max sum of the subarray. But here instead of finding the sum, we have to find the max gcd .

    • @spetsnaz_2
      @spetsnaz_2 Před 4 lety

      @@DEEPAKYADAV-vb2ee bro remember - maximum GCD value will always be equal to the largest number present in the array. Let’s say that the largest number present in the array is X. Now, the task is to find the largest sub-array having all X.

    • @techdose4u
      @techdose4u  Před 4 lety

      Max gcd will always be of length 2. So find all possible subarray gcds of length 2. There will be N-1 such subarrays.

  • @manjunathp9466
    @manjunathp9466 Před 3 lety +1

    l=list(map(int,input().split()))
    dic={}
    sum=maxarray=0
    for i in range(len(l)):
    sum+=(-1) if l[i]==0 else 1
    if sum==0:
    maxarray=i+1
    if sum not in dic.keys():
    dic[sum]=i
    else:
    maxarray=max(maxarray,i-dic[sum])
    print(maxarray)

  • @hemantranjan2297
    @hemantranjan2297 Před 2 lety

    2-0+1 = 2.

  • @spetsnaz_2
    @spetsnaz_2 Před 4 lety

    int findMaxLength(vector& nums) {
    // Fast I/O
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n = nums.size();

    if(n == 0 or n == 1)
    return 0;

    unordered_map mp;
    int res = 0, sum = 0;

    mp[0] = -1; //for handling first element as 0 so index is -1 default
    for(int i=0; i

  • @nuclearbaba1769
    @nuclearbaba1769 Před 10 měsíci

    can you give me solution for java

  • @lakshyavijh1249
    @lakshyavijh1249 Před 4 lety +2

    Laga de bhai sum wala concept 0 ko -1 rakhne wala

  • @abhinavsingh8675
    @abhinavsingh8675 Před 2 lety

    Naruto fan spotted

  • @BRBallin1
    @BRBallin1 Před měsícem

    I'm sorry but you were a bit hard to follow along

  • @gauthamsssomanna9388
    @gauthamsssomanna9388 Před 11 měsíci

    Java Solution
    Map sumMap = new HashMap();
    int sum = 0;
    int longestSubArr = 0;
    for (int i = 0; i < nums.length; i++) {
    sum += nums[i] == 0 ? -1 : 1; // make 0s as -1 and then add
    if (sum == 0) {
    longestSubArr = i + 1; // then we will put the index as the longestSubStr
    } else if (sumMap.get(sum) != null) {
    longestSubArr = Math.max(longestSubArr, i - sumMap.get(sum));
    } else {
    sumMap.put(sum, i);
    }
    }
    return longestSubArr;

  • @priyankadey3337
    @priyankadey3337 Před 3 lety +1

    Awesome explanation!