Rearrange Array Elements by Sign | 2 Varieties of same Problem

  Рет қаралды 220,560

take U forward

take U forward

Күн бұрын

Пікірлер: 368
@takeUforward
@takeUforward Жыл бұрын
Let's march ahead, and create an unmatchable DSA course! ❤ Use the problem links in the description.
@UECHarshaVardhanRavipalli
@UECHarshaVardhanRavipalli Жыл бұрын
Thanks for the consistency bhai!!!😇
@techyouknow8026
@techyouknow8026 Жыл бұрын
@take U forward bhai aise hi aapne sikha diya gara toh baaki ka pata nahi but main pakka google mein aaunga ,Hope You complete this course as soon posssible. Your video lectures are best!
@_CodeLifeChronicles_
@_CodeLifeChronicles_ 5 ай бұрын
this is undoubtfully an unmatchable dsa course
@BootCampResources
@BootCampResources 2 ай бұрын
Can you please explain in place approach using two pointer?
@AshishPrajapati-j7r
@AshishPrajapati-j7r 5 күн бұрын
I believe this can be one solution ``` const putInAlternativesOrder = (list) => { let pointer = 0; let positive_flag = true; for (let index = 0; index 0) { pointer++; positive_flag = false; } else if (list[index] > 0) { [list[index], list[pointer]] = [list[pointer], list[index]]; pointer++; positive_flag = false; } } else { if (list[pointer] < 0) { pointer++; positive_flag = true; } else if (list[index] < 0) { [list[index], list[pointer]] = [list[pointer], list[index]]; pointer++; positive_flag = true; } } } return list; }; ```
@manthenanagendra1077
@manthenanagendra1077 Жыл бұрын
Thank you striver because of you i was able to solve all 4 questions in todays leetcode contest..,you will definitely reach great heights for all the work you are doing
@aryansinha1818
@aryansinha1818 Жыл бұрын
Trust me I have watched all most all your videos but right now I feel the quality content, sound, depth of explanation, everything has reached an ultimate level. Ty for such an awesome content. Hope one day I will also have knowledge and confidence in DSA same as you.😀
@takeUforward
@takeUforward Жыл бұрын
Yes, with time I have understood, what exactly people need.
@vishnusiddarth7953
@vishnusiddarth7953 Жыл бұрын
@@takeUforward NICE BRO
@captain-ne8qy
@captain-ne8qy 4 ай бұрын
Review about striver....tree,graph and dp playlist??.....please !!
@aryansinha1818
@aryansinha1818 4 ай бұрын
@@captain-ne8qy wherever you go, the topics mentioned are must, bare minimum pick any sheet and solve 80-85% of the questions. My personal view on this, if you do TakeuForward you would grasp the concept well, it would definitely take some time, but you will be crystal clear and sound in the concept as well as solving questions. I think the sheet is designed in such a way and every question seems linked and connected. PS. This is totally based on my own understanding. Otherwise you can use KZbin and watch other channels too or search for individual questions and then do the topics .
@Maneeshce2007
@Maneeshce2007 10 ай бұрын
I find comments are the beginning of every video so true ... This is is unbelievable and the explanations are so crisp and clear. I am enjoying DS for the first time.
@sayantanpoddar5428
@sayantanpoddar5428 Жыл бұрын
UNDERSTOOD!! superb explaination ....PLEASE UPLOAD STRING VIDEO SERIES
@shubhamagarwal1434
@shubhamagarwal1434 3 ай бұрын
#Free Education For All.. # Bhishma Pitamah of DSA...You could have earned in lacs by putting it as paid couses on udamey or any other elaerning portals, but you decided to make it free...it requires a greate sacrifice and a feeling of giving back to community, there might be very few peope in world who does this...."विद्या का दान ही सर्वोत्तम दान होता है" Hats Off to you man, Salute from 10+ yrs exp guy from BLR, India....
@ParasSharma-mf8or
@ParasSharma-mf8or Жыл бұрын
0:00 Introduction of course 0:42: Rearrange array elements by sign(variety 1) 2:33 Brute force 4:30 Pseudo code (Brute force) 5:43 Optimal approach 8:36 Code-compiler (Optimal) 9:45 Variety 2 13:38 Pseudo code (Variety 2) 15:25 Code-compiler (Variety 2) 21:01 Outro
@stith_pragya
@stith_pragya 5 ай бұрын
Understood.....Thank You So Much for this wonderful video....🙏🏻🙏🏻🙏🏻🙏🏻
@vishalsharma9660
@vishalsharma9660 23 күн бұрын
Is bande ke course ke har video par like banta hain...so thoroughly explained.
@346_PrachiRaut
@346_PrachiRaut 7 ай бұрын
this man is literally an angel for devs
@chillin_08
@chillin_08 23 күн бұрын
How can the lectures be this amazing ✨.. You are a saviour to us for suree!!!
@manasranjanmahapatra3729
@manasranjanmahapatra3729 Жыл бұрын
UnderStood. Started Preparing Again. Just wanted to tell you I was a in Support Shifted to Development last year. Your content helped me a lot ❤💪.
@Mythri333
@Mythri333 18 күн бұрын
The best channel among all channels in world ❤..Thank you so much 😊
@Mb-nr5nz
@Mb-nr5nz Жыл бұрын
Thanks for giving such clear explanation, i understood each step you said from brute to optimal , question done 👍
@manvendrasinghrathore8100
@manvendrasinghrathore8100 9 ай бұрын
One word for you : King of explanation/knowledge
@sarangkumarsingh7901
@sarangkumarsingh7901 7 ай бұрын
Understood Sir...............Awesome Lecture...............
@cinime
@cinime Жыл бұрын
Understood! Super awesome explanation as always, thank you so much for your effort!!
@saswatrath4646
@saswatrath4646 7 ай бұрын
Bhaiya simplified appproach of your variety two Just the thing changed in the question is we have to insert negative at even indexes and positive at odd indexes a problem from code studio. #include void rearrange(vector &arr) { // Write your code here. int n = arr.size(); vector pos, neg; for (int i = 0; i < n; i++) { if (arr[i] < 0) { neg.push_back(arr[i]); } else { pos.push_back(arr[i]); } } int index = 0, i = 0, j = 0; while (i < pos.size() && j < neg.size()) { arr[index++] = neg[i++]; arr[index++] = pos[j++]; } while (i < neg.size()) { arr[index++] = neg[i++]; } while(j < pos.size()){ arr[index++] = pos[j++]; } // return; }
@haryanvibhajan001
@haryanvibhajan001 Ай бұрын
You don't need motivation , you are MOTIVATION!!!🏴‍☠🏴‍☠
@kingbadshah452
@kingbadshah452 10 ай бұрын
thanks striver understood everything
@brajeshmohanty2558
@brajeshmohanty2558 Жыл бұрын
Itna consistent ke se ho bhai thanks per mai morning Mai dekhuna ga🙏 love you
@arijit9862
@arijit9862 Жыл бұрын
Hey Striver! Here, "vector ans(n , 0)" this will also take a O(N) time, right? so technically it is O(2*N), isn't It ??
@takeUforward
@takeUforward Жыл бұрын
technically #include also takes a lot of time, usually, these things are not considered as we speak during interviews.
@md.ualiurrahmanrahat2400
@md.ualiurrahmanrahat2400 Жыл бұрын
The time complexity explanation for variety 2 problem was lit!!!
@prathameshjadhav2942
@prathameshjadhav2942 9 ай бұрын
Great explain
@aakashpatel1250
@aakashpatel1250 Жыл бұрын
Best explanation ever 🤩🙌
@samuelfrank1369
@samuelfrank1369 Жыл бұрын
Understood. Thanks a lot. Please upload more videos Bhaiyaaa
@aryansinha1818
@aryansinha1818 Жыл бұрын
What an awesome mic, really worth it!!
@sukhpreetsingh5200
@sukhpreetsingh5200 Жыл бұрын
Amazing explanation
@ankush8243
@ankush8243 10 ай бұрын
Thanks Bro💙 Keep teaching like this!! Appreciate your efforts!!
@Raj10185
@Raj10185 Жыл бұрын
My solution for the second variety :- #include using namespace std; int main() { vector arr = {-1,2,3,4,-3,1}; vector pos ; vector neg; for(auto it : arr) { if(it>= 0) pos.push_back(it); else neg.push_back(it); } if(pos.size()==neg.size()) { int k =0; int j =0; for(int i =0;i
@anuplohar23
@anuplohar23 10 ай бұрын
Hats off to your efforts Sir ❤❤
@Josuke217
@Josuke217 3 ай бұрын
Found the optimal solution on my own :) Great series Striver!
@shauryajain5358
@shauryajain5358 Жыл бұрын
Understood and thanks for another great lecture! Just a small confusion , I submitted the optimal solution for variety 1 on Leetcode but it took more time than the brute force solution. Why is that?
@divyanshujaiswal4682
@divyanshujaiswal4682 4 ай бұрын
for variety 2 i use 2 stack to store +ve and _ve elements and then pop one by one untill both the stacks are empty and store into an ans array.
@rohankadam7376
@rohankadam7376 Жыл бұрын
Super easy explanation, Thank you !!
@aniketgarg9575
@aniketgarg9575 Жыл бұрын
Such a wonderful explanation thank you sir 🙏
@infernogamer52
@infernogamer52 Жыл бұрын
Understood bhaiya!
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 9/28!!!
@srilathareddy9450
@srilathareddy9450 Жыл бұрын
Excellent explanation, understood
@hareshnayak7302
@hareshnayak7302 7 ай бұрын
Understood,Thanks srtiver for this amazing video.
@SahilKumar-vd7vj
@SahilKumar-vd7vj 7 ай бұрын
I think in this video you tell us the problem of alternative numbers - [-1,2,3,4,-3,1] the answer of this - [3,-1,4,-3,4,1] your answer is the very complex that you explain in this video, and when i ask to the chat gpt the answer will be very easy and understandable also, i am not comparing with AI but please do answer as much as that we remember long , and in your answer it is very difficult to remember the approach.
@NazeerBashaShaik
@NazeerBashaShaik 10 ай бұрын
Great explanation, thank you.
@dEviL_bIsWaJiT
@dEviL_bIsWaJiT 5 ай бұрын
Variety-2 - Alternate solution(C++) vectorpos; vectorneg; for(int i=0;i=0){ pos.push_back(arr[i]); } else{ neg.push_back(arr[i]); } } int i=0; int j=0; arr.clear(); while(i
@jineshnadar6409
@jineshnadar6409 Жыл бұрын
Variety 2 without using the extra spaces for pos and neg. class Solution: def rearrangeArray(self, nums): ls = [ 0 ] * len( nums ) pos = 0 neg = 1 minCount = 0 for i in range( len( nums )): if nums[ i ]> 0: minCount +=1 negNumsAreMin = False if minCount > len( nums ) - minCount: negNumsAreMin = True minCount = len( nums ) - minCount count = 0 for i in range( len( nums )): if nums[ i ] > 0: ls[ pos ] = nums[ i ] if negNumsAreMin: if ( count < minCount ): pos +=2 else: pos += 1 count +=1 else: pos += 2 else: ls[ neg ] = nums[ i ] if negNumsAreMin == False: count +=1 if ( count < minCount ): neg +=2 else: neg += 1 else: neg += 2 return ls s = Solution() print(s.rearrangeArray([-1,-2,-3,-4,1,2,3,4,5,6,7]))
@aliakbaransaria3-925
@aliakbaransaria3-925 Жыл бұрын
Very good explanation keep it up
@RealRaghu09
@RealRaghu09 6 ай бұрын
We can also do swaping with odd index element with even index element if element are positive or negative Time Complexity is O(N)
@VENUGOPALRAO-w6h
@VENUGOPALRAO-w6h Жыл бұрын
thanks you for your explanation I understood it but sir can this be solved using pointers
@mehaksharma7959
@mehaksharma7959 5 ай бұрын
i have a question do I need to first try to solve the problem by myself then watch video or should i watch videa then solve the problem myself?
@ravansingh6325
@ravansingh6325 Жыл бұрын
I think in second variety 2 pointer solution will be the optimal one.
@MohitKumar-o3l1u
@MohitKumar-o3l1u 9 ай бұрын
Understood.
@ijatin1213
@ijatin1213 9 күн бұрын
Variety 2: Done using 3 For Loops vector alternateNumbers(vector&a) { vector pos ; vector neg; for(int i = 0; i< a.size(); i++){ if(a[i] >= 0) { pos.push_back(a[i]); } else{ neg.push_back(a[i]); } } for(int i = 0 ; i < pos.size() ; i++){ a[2*i] = pos[i]; } for (int i = 0; i < neg.size(); i++) { a[2 * i + 1] = neg[i]; } return a; };
@The_yellow_flash-07
@The_yellow_flash-07 3 ай бұрын
it was brilliant.
@DevashishJose
@DevashishJose Жыл бұрын
Understood, Thank you so much
@jatinkaushik2607
@jatinkaushik2607 Жыл бұрын
Instead of collecting the nums in two array, can we do like catch the count of pos and negative numbers and use loop as per greater count conditions? this one is also optimised instead of using space of two array we are counting on reference variables.
@takeUforward
@takeUforward Жыл бұрын
We can, it is pretty much the same if you consider tc and sc
@Aditi_krishna
@Aditi_krishna 3 ай бұрын
is it possible to optimise space complexity using swaping????????????
@rwordspecialist6734
@rwordspecialist6734 2 ай бұрын
Using pointers??
@rachitsingh2013
@rachitsingh2013 Жыл бұрын
Do you, at any point in the near future, think of creating a backend development course?
@xoxoxo7313
@xoxoxo7313 Жыл бұрын
Great explanation Striver !!!
@gourabbhattacharjee2128
@gourabbhattacharjee2128 Жыл бұрын
Any Java people, here's a short code using functional programming.. public int[] rearrangeAltPosNeg(int[] arr) { var res = new int[arr.length]; var pos = Arrays.stream(arr).filter(num -> num >= 0).toArray(); var neg = Arrays.stream(arr).filter(num -> num < 0).toArray(); var cmnSize = Math.min(pos.length, neg.length); for (var i = 0; i < cmnSize; i++) { res[2 * i] = pos[i]; res[2 * i + 1] = neg[i]; } var remArr = pos.length > neg.length ? pos : neg; System.arraycopy(remArr, cmnSize, res, cmnSize * 2 , arr.length - cmnSize * 2); return res; }
@priyanshughosh6143
@priyanshughosh6143 3 ай бұрын
both the problem links are pointing to same question. plz provide us with the correct links
@konankikeerthi
@konankikeerthi 5 ай бұрын
Understood bro. Thank you
@GhostVaibhav
@GhostVaibhav Жыл бұрын
Understood🔥
@priyankagarg3891
@priyankagarg3891 4 ай бұрын
Can it be solved in O(1) space complexity?
@gossgowtham
@gossgowtham Жыл бұрын
Understood both!
@pushkardeore4324
@pushkardeore4324 7 ай бұрын
in the first variety, what if we first put all the positive numbers before the negatives in O(N) complexity like we sorted ones and zeros, and then again rearrange them in the alternate manner with another O(N/2) complexity? so that tc=O(2N) and sc=O(1)
@charan123rams3
@charan123rams3 Жыл бұрын
Thank you so much sir 🥰
@isheep9025
@isheep9025 Жыл бұрын
self note: the following does the same in 0(1) extra space but does not preserve the original order if positive and negative elements class Solution { public: vector rearrangeArray(vector& nums) { int temp=-1; for(int i=0;i
@saikumargatla4706
@saikumargatla4706 Жыл бұрын
Hey striver what if zero is present in array will it be considered pos or neg .or else it is stated that array will have no zeros
@smritiii7697
@smritiii7697 Ай бұрын
0 is also +ve ig
@abhijeetmishra3804
@abhijeetmishra3804 Жыл бұрын
understood. but bhaiya how to remember this many algos like array has then linked list stack queue tree graph and all this how will we remember so many codes and algorithm during interview?
@Se7ven_Plays
@Se7ven_Plays Жыл бұрын
Love you bro I'll watch it later
@Curiosity_hub2404
@Curiosity_hub2404 Жыл бұрын
can we really rearrage it i th same array...is there any way to do that?
@AbhishekPandey-dj2eo
@AbhishekPandey-dj2eo Жыл бұрын
Keep the good work going on
@mr_noob6361
@mr_noob6361 Жыл бұрын
Hii sir .....i am not like a wizard coder as like you ..but i made 2nd variety in o(n) pass here is my code.... arr1=[3,1,-2,-5,2,-4] #not using any extra space # for i in range(len(arr1)): # if(i%2==0):#even index # if(arr1[i]>0): # continue # else: # #kya pata woh negative hoo # for j in range(i+1,len(arr1)): # if arr1[j]>0: # arr1[j],arr1[i]=arr1[i],arr1[j] # break # else: # if(arr1[i]
@ronitakhariya4094
@ronitakhariya4094 11 ай бұрын
Hello Great job in writing these codes. i saw both of them and noticed that yes the first code is not taking any extra space so sc is O(1) but the time complexity for worst case will be o(n^2) if all your values are negative or all are positive since its not gonna break from the nested for loop and around O(n^2) if all elements are negative except the last one and so on. In your second solution you changed time complexity from O(2N) to O(N) however when calculating time complexity for larger inputs we tend to ignore the constant part in big O notation for analysing scalability and efficiency. so it does't exactly optimise the solution. I wrote this comment to just clear doubts in new students and not to criticise your solution.
@mr_noob6361
@mr_noob6361 11 ай бұрын
@@ronitakhariya4094 😊😊 thanks
@smartcreation2671
@smartcreation2671 6 ай бұрын
is Big O(2n) == Big O(n)
@gagan_.hegde14
@gagan_.hegde14 6 ай бұрын
no
@Mrindia-k8n
@Mrindia-k8n Ай бұрын
00:06 Rearrange array Elements by sign 02:18 Rearrange positive and negative numbers maintaining their order 04:14 The solution involves rearranging elements in an array by separating positive and negative elements. 06:34 Implementing the optimal approach for array reversal 08:53 If positive is not equal to negative, there can be two cases: either the number of positives are greater than negatives or the number of negatives are greater than positives. 11:01 There can be two cases: either the number of positives is greater than negatives, or the number of negatives is greater than positives. 13:18 Algorithm for arranging positive and negative numbers in alternate order 15:31 Separate positive and negative elements in an array 17:30 Extract positive and negative dots from given data. 19:30 The worst complexity of the problem is O(n).
@momentcoder
@momentcoder 18 күн бұрын
Understood ✅
@swastiktiwari7066
@swastiktiwari7066 8 ай бұрын
First variety doing in place without creating answer vector: class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: n = len(nums) w = 20 # num bits for number, w+1 (0-idx) is sign bit inneg = 1
@Editzx.10
@Editzx.10 5 ай бұрын
Understood Champ!
@samridhiarora4014
@samridhiarora4014 Жыл бұрын
00:06 Rearrange array Elements by sign 02:18 Rearrange positive and negative numbers maintaining their order 04:14 The solution involves rearranging elements in an array by separating positive and negative elements. 06:34 Implementing the optimal approach for array reversal 08:53 If positive is not equal to negative, there can be two cases: either the number of positives are greater than negatives or the number of negatives are greater than positives. 11:01 There can be two cases: either the number of positives is greater than negatives, or the number of negatives is greater than positives. 13:18 Algorithm for arranging positive and negative numbers in alternate order 15:31 Separate positive and negative elements in an array 17:30 Extract positive and negative dots from given data. 19:30 The worst complexity of the problem is O(n). 21:19 Follow me on all social media handles
@placement123
@placement123 4 ай бұрын
can it be done without extraaa space??
@amithkotian7556
@amithkotian7556 Жыл бұрын
Good one.. understood
@bharathi66
@bharathi66 4 ай бұрын
Understood Bhaiya
@rumiNITPatna
@rumiNITPatna 8 күн бұрын
amazing video!
@_hulk748
@_hulk748 Жыл бұрын
Understood sir❤🙏🙇‍♂
@tamilmukbang3789
@tamilmukbang3789 6 ай бұрын
understood thank you bro
@heyOrca2711
@heyOrca2711 7 ай бұрын
Understood Sir!
@AniketKumar-hf2bo
@AniketKumar-hf2bo 9 ай бұрын
UNDERSTOOD ❤❤❤❤👌👌
@ksankethkumar7223
@ksankethkumar7223 Жыл бұрын
Now the problem is changed same as variety 1 in CodeStudio too!!
@takeUforward
@takeUforward Жыл бұрын
OOps :|
@gautamsaxena4647
@gautamsaxena4647 Ай бұрын
understood bhaiya
@mehaksharma7959
@mehaksharma7959 5 ай бұрын
and one more thing I try to solve the problem after a few days the one thing that i remember is brute force , i sometimes forget the optimal solution like for algos like kadanes
@kk420100
@kk420100 4 ай бұрын
i always use this approach..it's a generic approach - Step1. Solve a problem using B Force Step2. For the Better Solution try using 1 for loop Step3. Better solution 2 - Try using hashing Step4. Optimal Solution if any for this question, your default approach should be converting 2 or more for loop to 1 for loop. Here that will be also the optimal solution. In this case, it's just a re-write of BF
@per.seus._
@per.seus._ Жыл бұрын
under❤stood
@oyeesharme
@oyeesharme 2 ай бұрын
thanks bhaiya
@shaiksoofi3741
@shaiksoofi3741 9 ай бұрын
Thank you
@prabhagaikwad4849
@prabhagaikwad4849 Жыл бұрын
Understood as always 😍
@Ayushsharma-qc7qx
@Ayushsharma-qc7qx 8 ай бұрын
Understand
@dummyaccount5960
@dummyaccount5960 7 ай бұрын
This is the question of easy type. Donno why it is in the category of Medium in A2Z DSA Sheet...
@vineetmittal3837
@vineetmittal3837 Жыл бұрын
For first variety of problem my solution would be : int j = 0; for (int i=0; i < n; i++){ while (j = 0) || (j%2 != 0 && arr[j] < 0)){ j++; } else { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; break; } } } This is not using any extra space and time complexity is O(n). Please correct me if there is any mistake.
@tejas7379
@tejas7379 Жыл бұрын
I think time complexity is O(n^2)
@tanishkumar6682
@tanishkumar6682 Жыл бұрын
understood
@Adityakumar-dl4vc
@Adityakumar-dl4vc Ай бұрын
Thank
@AbhishekKumar-cv1dh
@AbhishekKumar-cv1dh Жыл бұрын
Understood !! 🔥🔥
@AbhishekBhattacharjee-j2m
@AbhishekBhattacharjee-j2m Жыл бұрын
UNDERSTOOD
Next Permutation - Intuition in Detail 🔥 | Brute to Optimal
28:15
take U forward
Рет қаралды 442 М.
Kadane's Algorithm | Maximum Subarray Sum | Finding and Printing
20:09
take U forward
Рет қаралды 473 М.
My MEAN sister annoys me! 😡 Use this gadget #hack
00:24
JOON
Рет қаралды 1,5 МЛН
Car Bubble vs Lamborghini
00:33
Stokes Twins
Рет қаралды 35 МЛН
Who's spending her birthday with Harley Quinn on halloween?#Harley Quinn #joker
01:00
Harley Quinn with the Joker
Рет қаралды 17 МЛН
DP 35. Best Time to Buy and Sell Stock | DP on Stocks 🔥
9:11
take U forward
Рет қаралды 401 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 658 М.
My MEAN sister annoys me! 😡 Use this gadget #hack
00:24
JOON
Рет қаралды 1,5 МЛН