Contiguous array | Leetcode

Поділитися
Вставка
  • Опубліковано 9 січ 2025

КОМЕНТАРІ •

  • @anand_dudi
    @anand_dudi 10 місяців тому +5

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

  • @shivanggupta5421
    @shivanggupta5421 4 роки тому +32

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

  • @goutamkundu6392
    @goutamkundu6392 3 роки тому +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.

  • @gourabbanerjee4152
    @gourabbanerjee4152 4 роки тому +6

    The best explanation for this problem! Good Job!

  • @aadil4236
    @aadil4236 10 місяців тому

    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.

  • @aparnamane1164
    @aparnamane1164 4 роки тому +4

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

  • @lemax2980
    @lemax2980 4 роки тому +7

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

  • @qilin78
    @qilin78 4 роки тому +4

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

  • @PremPal-uy4nm
    @PremPal-uy4nm 2 роки тому +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.

  • @pranayraj7938
    @pranayraj7938 4 роки тому +4

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

  • @abhijitbandyopadhyay4821
    @abhijitbandyopadhyay4821 5 місяців тому

    Good Explanation. Clear & concise.

  • @najimali32
    @najimali32 4 роки тому +6

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

  • @aswathsrimarir2501
    @aswathsrimarir2501 4 роки тому +2

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

  • @juuzousuzuya69
    @juuzousuzuya69 7 місяців тому

    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

  • @bisheshwardevsharma3243
    @bisheshwardevsharma3243 6 місяців тому +1

    Thank you. It was a good explanation

  • @venkateshthirunagiri85
    @venkateshthirunagiri85 4 роки тому +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  4 роки тому +8

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

  • @meet2637
    @meet2637 4 роки тому +1

    This channel is gold.

  • @ryanchen467
    @ryanchen467 2 роки тому

    The is the best explanation I've seen

  • @sumitSharma-ed5mi
    @sumitSharma-ed5mi 3 роки тому +1

    Very good explanation and its very helpful

  • @ganeshjaggineni4097
    @ganeshjaggineni4097 7 місяців тому

    NICE SUPER EXCELLENT MOTIVATED

  • @halfaddercircuit
    @halfaddercircuit 3 роки тому

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

  • @aviligondagowtham1153
    @aviligondagowtham1153 4 роки тому +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  4 роки тому

      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 4 роки тому +1

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

    • @techdose4u
      @techdose4u  4 роки тому +2

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

    • @akshitajha1209
      @akshitajha1209 2 роки тому

      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!

    • @pravyn350
      @pravyn350 4 місяці тому

      @@techdose4u better move to python 🐍 sir

  • @akhilesh59
    @akhilesh59 2 роки тому +2

    Thanks for the explanation :)

  • @anjalisinha3377
    @anjalisinha3377 4 роки тому +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

  • @kumarswamy3554
    @kumarswamy3554 3 роки тому +1

    very clear explanation. Thank you so much.

  • @Ankit-jn8ew
    @Ankit-jn8ew 4 роки тому +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  4 роки тому

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

    • @Ankit-jn8ew
      @Ankit-jn8ew 4 роки тому +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  4 роки тому

      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.

    • @Ankit-jn8ew
      @Ankit-jn8ew 4 роки тому

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

  • @chrisjurgens8043
    @chrisjurgens8043 Рік тому

    Great explanation, helped me solve for sure!

  • @dhanashreegodase4445
    @dhanashreegodase4445 2 роки тому +1

    Keep posting. Thankyou.

  • @ajaywadhwa3398
    @ajaywadhwa3398 4 роки тому +1

    Really Impressive. Helped a lot !!

  • @sarvesh6785
    @sarvesh6785 2 роки тому +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

  • @Giri14_18
    @Giri14_18 10 місяців тому

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

  • @mohamedhesham6008
    @mohamedhesham6008 2 роки тому

    That's really amazing explanation

  • @akshayaamar9825
    @akshayaamar9825 2 роки тому +1

    Very well explained. Thank you.

  • @ahmedfouzan
    @ahmedfouzan 2 роки тому +1

    Thanks for the clear explanation

  • @abhishekkumarjhariya1340
    @abhishekkumarjhariya1340 2 роки тому +2

    Great explanation as always.

  • @Yash-uk8ib
    @Yash-uk8ib 4 роки тому +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  4 роки тому +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 4 роки тому +2

      @@techdose4u ohhkk... i got it

    • @techdose4u
      @techdose4u  4 роки тому

      :)

    • @stankafan6688
      @stankafan6688 4 роки тому +2

      hahaha bhaiya i too thought same for the first time 😅

    • @soumavabanerjee5925
      @soumavabanerjee5925 2 роки тому

      I tried this one too at first and got WA XD

  • @subham-raj
    @subham-raj 4 роки тому +3

    *Closer to prefix sums*

  • @saurabh.gupta22
    @saurabh.gupta22 9 місяців тому

    Great Explanation ❤

  • @praveenchouhan6388
    @praveenchouhan6388 4 роки тому +2

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

  • @priyamani4349
    @priyamani4349 4 роки тому +2

    Great work.

  • @ganakkathuria4893
    @ganakkathuria4893 2 роки тому +1

    Nice explanation

  • @suryajanardhan
    @suryajanardhan 10 місяців тому

    very good explanation

  • @priyankadey3337
    @priyankadey3337 3 роки тому +1

    Awesome explanation!

  • @Learner010
    @Learner010 4 роки тому +1

    the best explanation!!

  • @ishmeetbindra5428
    @ishmeetbindra5428 4 роки тому +1

    Nicely Explained!

  • @debashisdas6593
    @debashisdas6593 4 роки тому +1

    Nice explanation !!!

  • @shubhamgarg7198
    @shubhamgarg7198 4 роки тому +2

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

    • @techdose4u
      @techdose4u  4 роки тому +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.

  • @tanishqaggarwal1197
    @tanishqaggarwal1197 Рік тому

    Nice approach

  • @kushgupta1187
    @kushgupta1187 4 роки тому

    Very well explained

  • @audioplatform6299
    @audioplatform6299 3 роки тому +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  3 роки тому

      Generally you won't be asked hard problems.

  • @jaydeepmahajan6598
    @jaydeepmahajan6598 4 роки тому +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  4 роки тому +1

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

  • @mayankchauhan6680
    @mayankchauhan6680 4 роки тому +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  4 роки тому +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.

  • @ryan.aquino
    @ryan.aquino 4 роки тому

    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

  • @sujiths9199
    @sujiths9199 2 роки тому

    I really appreciate your thought process

  • @nidhisingh25_
    @nidhisingh25_ 4 роки тому +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  4 роки тому

      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.

  • @ApexPlayground_divine
    @ApexPlayground_divine 3 місяці тому

    Thanks brother, explanation was so good , i could solve without waiting for code section.

  • @syed7996
    @syed7996 4 роки тому +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  4 роки тому +1

      Will make it in near future for sure :)

  • @ssaha7714
    @ssaha7714 2 роки тому

    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

  • @rahulsaini202
    @rahulsaini202 3 роки тому +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  3 роки тому +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 3 роки тому

      @@techdose4u Thanks for the response.

  • @parekshamanchanda8083
    @parekshamanchanda8083 4 роки тому +1

    Can be done with stack as well

  • @vinoltauro9160
    @vinoltauro9160 4 роки тому

    can we use the sliding window technique ?

  • @damodaranm3044
    @damodaranm3044 4 роки тому +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  4 роки тому +1

      Thanks bro :)

    • @damodaranm3044
      @damodaranm3044 4 роки тому

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

  • @stankafan6688
    @stankafan6688 4 роки тому

    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

  • @akshitajha1209
    @akshitajha1209 2 роки тому +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  2 роки тому +1

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

  • @najimali32
    @najimali32 4 роки тому

    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

  • @manjunathp9466
    @manjunathp9466 4 роки тому +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)

  • @muskanmangal8938
    @muskanmangal8938 4 роки тому +1

    It helped!

  • @subhadippatra7930
    @subhadippatra7930 4 роки тому +1

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

    • @techdose4u
      @techdose4u  4 роки тому

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

  • @akashmittal7795
    @akashmittal7795 4 роки тому +3

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

    • @techdose4u
      @techdose4u  4 роки тому +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 4 роки тому

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

  • @muskaangupta4920
    @muskaangupta4920 4 роки тому +1

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

    • @techdose4u
      @techdose4u  4 роки тому

      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 4 роки тому +1

      Okay. Got it!!

    • @techdose4u
      @techdose4u  4 роки тому

      👍

  • @amanvijayvargiya3468
    @amanvijayvargiya3468 4 роки тому +1

    thank you so much ..

  • @rahulchaubey8988
    @rahulchaubey8988 4 роки тому +1

    👌👌👌👌👌👌

  • @baxtables
    @baxtables 3 роки тому

    is it a dp problem?

  • @yashshreeshinde4394
    @yashshreeshinde4394 3 роки тому +1

    Thank you!!!!

  • @ankitchaturvedi2941
    @ankitchaturvedi2941 2 роки тому

    can we solve it without map

  • @locusoflearning
    @locusoflearning 4 роки тому +1

    Thanku sir.

  • @DEEPAKYADAV-vb2ee
    @DEEPAKYADAV-vb2ee 4 роки тому +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  4 роки тому +1

      What can be the size of subarray?

    • @DEEPAKYADAV-vb2ee
      @DEEPAKYADAV-vb2ee 4 роки тому

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

    • @DEEPAKYADAV-vb2ee
      @DEEPAKYADAV-vb2ee 4 роки тому

      @@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 4 роки тому

      @@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  4 роки тому

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

  • @spetsnaz_2
    @spetsnaz_2 4 роки тому

    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

  • @sahilanand30
    @sahilanand30 2 роки тому +1

    You just explained the solution
    But there is no intuition

  • @nuclearbaba1769
    @nuclearbaba1769 Рік тому

    can you give me solution for java

  • @lakshyavijh1249
    @lakshyavijh1249 4 роки тому +2

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

    • @techdose4u
      @techdose4u  4 роки тому +2

      😂

    • @lakshyavijh1249
      @lakshyavijh1249 4 роки тому

      @@techdose4u bhai placement h 🤣bta de kaise padu

    • @techdose4u
      @techdose4u  4 роки тому

      Bhai target company btao...fir kuchh btate hain 😅

    • @lakshyavijh1249
      @lakshyavijh1249 4 роки тому

      @@techdose4u bhai flipkart ya amazon

  • @hemantranjan2297
    @hemantranjan2297 2 роки тому

    2-0+1 = 2.

  • @abhinavsingh8675
    @abhinavsingh8675 2 роки тому

    Naruto fan spotted

  • @BRBallin1
    @BRBallin1 7 місяців тому

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

  • @gauthamsssomanna9388
    @gauthamsssomanna9388 Рік тому

    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;