At 23:47 my mind just got blown away. Me be like: - itna easy kese Benstocks 😂🙏. Bhai iPad ka notes ka bhi pdf dalo na . Tumaaher writing sei sab samajh mai ata hai. Boh tuf sight par itna bada article dekhne sei dar lagta hai 🙂. But you are doing amazing job bhai thank you 🙏😌.
for moving zeroes to the end we cen write it in 1 loop instead of two though time complexity is same , complexity for understanding decreases : v oid moveZeroes(vector& nums) { int j=0; for(int i=0;i
@@helloworld-n1z I am not the right person but still always go back to the code after a week or so and try solving it again. Then review it after a month. That is it, it will get hard coded in your brain after that.
Thanks a lot sir for taking out time from your busy schedule and making videos and uploading those videos in the span of 2-3 days. It takes a lot ot effort. Thanks a lot 😊😊
Timestamps: 0:00:00 - Intro 0:00:55 - Q1. Left rotate an array by 1 place 0:07:33 - Q2. Left rotate an array by D places 0:26:36 - Follow up Right rotate an array by D places 0:27:11 - Q3. Moving Zeroes to end 0:40:54 - Q4. Linear Search 0:43:01 - Q5. Union of Two Sorted Arrays 0:59:04 - Q6. Intersection of Two Sorted Arrays 1:12:22 - Outro
For Right Rotation of Array void rotate(vector arr, int d) { if(d>size) d = d % size; reverse(arr.begin(),arr.end()); reverse(arr.begin()+d,arr.end()); reverse(arr.begin(),arr.begin()+d); }
First Understanding the problem then finding approach to solve it then if I make the correct solution then codding it in vs code and moving to nxt question and if I didn't get the solution then watching striver
27:00 rotating an array left by 1 place is equal to rotating it right by n-1 places. We can use this information for rotating an array to right by d places.
✦ Learn left rotation of an array by one place 00:03 ✦ Understand the difference between space used and extra space in algorithms. 06:07 ✦ Learn how to left rotate an array in C++ or Java 18:42 ✦ Left rotate an array by D places 24:15 ✦ Use two pointer approach to move zeros to the end of an array. 34:25 ✦ Summary of array problems 40:19 ✦ Implementing a pointer approach to find the union of two sorted arrays. 50:18 ✦ Union and intersection of sorted arrays 55:30 ✦ Optimize time complexity using two pointer approach 1:06:02 ✦ Optimal solution for intersection of two sorted arrays Click to expand 1:11:14
One thing striver..... In the sheet for the same question as we know there is a link attached for the gfg version and for the leetcode version but in some cases leetcode version is harder and sometimes gfg version. So please pick the hard problem for that
I am keeping my promise, if you see am covering 5 problems in one video. So recording such a long video, then editing it, then uploading it takes time. I can upload daily, if you want me to to cover one video.
//HOMEWORK FOR ROTATE RIGHT class Solution { public: void rotate(vector& nums, int k) { k = k % (nums.size()); int n = nums.size(); vectortemp; for(int i = n-k; i
Thank you brother if your infront of me i would have clean your feet with water 💦 because I ever seen tutor like you and your tutorials are more than a 10 lak rupees ❤❤❤
I always thought that the optimal solution to this code was the hashset one that you did in the middle part. It blew my mind when I saw the optimal one... And that too so easy man... Wow .. just wow to your observation ❤
Wrong Logic at 40:46 (Move Zeros to End ) what if the Array element is {1,0} at the first iteration your j=1 means you found zero element at index 1, Now you found first non zero element at 0 index you swap nums[i] and nums[j] now array look like this {0,1} and j is now 2 since i=1 means loop will run one more time bcz i is less than size of array i-e 2, Again you find non-zero element at index 1 i-e 1 you try to swap nums[1] and nums[2] You will end up with an Runtime error ArrayIndexOutOfBound.
for the first time i guessed which concept can be used it might sound like a small thing but as a beginner who is just learning to code actually implementing codes without any reference and knowing which loop is used is really HUGE for me. THANK YOU SOO MUCH
bhaiya intersection of two array waale concept m jab aapne final arry nikala tab aapne 3 ko two time liya h but intersection mein toh common element aata h aur vo bhi one time hi aata h?
How do you know if the first index i.e. i=0, will always going to be zero? Also you cannot initiate j from 0, if arr[] = {1,2,3,0}, both I and j will point to 1 and since they both are non zero elements, you are swapping them with themselves only.
Bhiya arrays k dsa m list kaa zikrr kyu krna, list have method to add but arrays don't have.. I know you are well versed in your profession but ek dikkat h beginners ko hoti h when they heard About list and trying to implement it in arrays😢, just my point of view hope you understand
GUYS THIS MY BRUTE FORCE APPROACH PLEASE TELL ME IS RIGHT OR WRONG 🙏🙏🙏 import java.util.ArrayList; public class Step3_Arrays { static void EndZeros(int []arr,int n){ ArrayList TempArraylist1=new ArrayList(); ArrayList TempArraylist2=new ArrayList(); for(int i=0;i
i think i got a better solution for move zeroes to end, If im wrong please correct me void Solve2(int arr[] , int arrl) //O(n) with space complexity O(1) {Only 1 variable } { int counter =0; for(int i=0;i
0:00 Introduction of course 01:01 Left rotate an Array by 1 Place 04:38 Pseudo code 07:17 Code-compiler 08:05 Left rotate an Array by D Places 14:38 Pseudo code 20:18 Code-compiler 27:13 Move zeroes to end 37:41 Pseudo code 40:30 Code-compiler 41:05 Linear search 42:01 Pseudo code 42:43 Code-compiler 43:04 Union of two sorted array 53:33 Code-compiler 59:05 Intersection of two sorted array 1:09:30 Code-compiler
Great! btw in the worst case of Intersection, the space complexity would be O(n1>n2?n2:n1) because whichever one is smaller matches completely with the other array and ends. P.S.- the space is for returning the answer and not solution.
Understood 😄. Logic used for right rotate the array k places is that instead of rotating array right by k places I have rotated it n-k places to left . so code for this is - class Solution { public: void rotate(vector& nums, int k) { int n = nums.size(); k = k % n; reverse(nums.begin(),nums.begin()+(n-k)); reverse(nums.begin()+(n-k),nums.end()); reverse(nums.begin(),nums.end()); } };
why my output is not coming????? 349. Intersection of Two Arrays class Solution { public: vector intersection(vector& nums1, vector& nums2) { int i=0; int j=0; int n1=nums1.size(); int n2=nums2.size(); vector ans; while(i
In the brute force approach of union of arrays, you could have directly returned the set instead of taking a temp vector and copying it all over, because the set would only take the single copies of the elements are the time of insertion
bro you are right but most of the time they i.e., dsa practicing websites expect you to return the result in the form of array(for c++ vector and for Java ArrayList).
how about using recursion for left rotation at 0:24:00 ??? void left_rotate_better(int arr[],int n,int d) { d=d%n; if(d==0) return; int temp=arr[0]; for(int i=1;i
it took me an hour to do rotate by K problem now even i don't remember how i did this ```js function a(len,jk){ if(jk >= 0) return jk if(jk < 0){ const b = len - Math.abs(jk) return a(len, b) } } var rotate = function(nums, k) { const copyArr = [...nums] for(let j = 0; j < nums.length; j++){ const replacement = a(nums.length, j-k) nums[j] = copyArr[replacement] } return nums }; ~```
Actually, there is another optimal solution for moving zeroes problem. It is similar to the function we use in quicksort algorithm (quickselect part for arranging elements around pivot). void Optimal2(̀vector& nums) { int j=-1, n=nums.size(); for(int i=0; i
Assignment:- "Right rotate an array by k places" class Solution { public void rotate(int[] nums, int k) { int[] ans = new int[nums.length]; for(int i = 0; i < nums.length; i++){ ans[(i+k) % nums.length] = nums[i]; } for(int i = 0; i < nums.length; i++){ nums[i] = ans[i]; } } }
Hey striver wonderful video. I have a query. The code will be applicable only if the vector or array is sorted in the intersection part. So do we need to sort it again or is there any other optimal approach ?
conscise solution for move zeroes to end class Solution { public: void moveZeroes(vector& nums) { int n = nums.size(); int j = 0; for (int i = 0; i < n; i++) { if (nums[i] != 0) { swap(nums[i], nums[j]); j++; } } } };
For the instersection question,why don't you consider temp array/vector space in addition to visted array for space complexity(brute force) ,because that too is used?.And for the optimal solution space complexity must be O(min(n1,n2)) if all elements are common??...
Right rotate array by d places is equivalent to left rotate array by n-d places. void rightRotateArrayOptimal(int arr[],int n,int d){ d = d%n; d = n-d; reverse(arr,arr+d); reverse(arr+d,arr+n); reverse(arr,arr+n); }
move all zeroes to end of array this is same approch but some lines of code are different from that of strivers!!!!! void pushZerosToEnd(int arr[], int n) { // code here int i=0; int j=i+1; while(j
got confused with move zero to end problem easy solution class Solution{ public: void pushZerosToEnd(int arr[], int n) { // code here int i=0,j=0; //int size=n; while( i
why am I getting the 'this is taking too long' for the intersection problem using the first approach? can you please explain? #include vector findArrayIntersection(vector &arr1, int n, vector &arr2, int m) {
🎯 Key Takeaways for quick navigation: 00:56 🔄 *Left rotate an array by one place involves moving elements one place ahead. Optimal solution involves in-place rotation without using a new array.* 05:26 ⏰ *Time complexity of left rotation by D places is O(N+D). Extra space complexity is O(D) due to the use of a temporary array.* 12:20 🤔 *When left rotating an array by D places, D can be reduced to D mod N, as multiples of N rotations bring the array back to its original state.* 20:37 ⚙️ *Optimal solution avoids using extra space by reversing the array elements in three steps: reverse the whole array, reverse the first D elements, and reverse the remaining N-D elements.* 23:04 🔄 *The speaker explains a method to rotate an array to the left by a given number of places using three reverse operations.* 27:12 🔄 *The problem of moving zeros to the end of an array is introduced, and a Brute Force approach is discussed, involving identifying non-zero numbers, moving them to the front, and filling the remaining positions with zeros.* 33:45 🔄 *An optimal solution for moving zeros to the end is presented, using a two-pointer approach to efficiently move non-zero elements to the front while iterating through the array.* 40:57 🧐 *Linear search is introduced as the problem of finding the first occurrence of a given number in a sorted array. The speaker presents a Brute Force approach involving iterating through the array and checking for equality.* 43:04 🧑🤝🧑 *The problem of finding the union of two sorted arrays is discussed, emphasizing the need for an optimal solution. The speaker starts with a Brute Force approach involving combining both arrays and removing duplicates.* 44:40 🧭 *Brute force approach for finding the union of two sorted arrays involves using a set data structure to ensure uniqueness and sorted order.* 50:22 🚥 *Optimal approach for finding the union of two sorted arrays uses a two-pointer approach to efficiently iterate through both arrays, considering unique elements.* 53:39 🕰️ *The time complexity of the optimal approach for finding the union is O(N1 + N2), where N1 and N2 are the sizes of the two arrays.* 59:00 🤝 *Brute force approach for finding the intersection of two sorted arrays involves checking for corresponding elements and using a visited array to ensure uniqueness.* 01:05:59 🔄 *The time complexity of the brute force approach for finding the intersection is O(N1 * N2), where N1 and N2 are the sizes of the two arrays.* 01:06:13 🧠 *Brute Force approach for array intersection involves checking every element in both arrays for a match, leading to a time complexity of O(N1 * N2).* 01:07:32 🔄 *Optimal solution for intersection utilizes a two-pointer approach due to sorted arrays, resulting in a time complexity of O(N1 + N2) and no extra space usage.* 01:09:48 🤖 *Implementing the optimal solution involves iterating through both arrays, comparing elements, and building the intersection array with minimal space complexity.* Made with HARPA AI
In MAANG interview generally the coding round is of 45 min and they ask 2-3 LC medium questions.So, approx. 15 min(discuss + solve) for 1 question if 2 medium LC question they asked. So, if we know optimal solution then discussing on brute force approach will cost us. So, any suggestion here ?
In the three reversals, we are doing iterations just for half the time i.e O(d/2) + O((n-d)/2) + O (n/2) making it O(n) so TC as well as SC of optimal solution is better than the better solution.
in the brute force solution of the interscetion of two array , the code will be correct even if i dont use break statement , only the number of iterations will increase , but in the given problem link , its not showing the correct answer in that case (if i am not using the break case)
left rotation to right rotation: simple approach is to think oppositely to left rotation. Shift all elements right of d and add to temp and push it. Just reverse the order of the reverse statements used in left rotation!.
OPTIMAL CODE FOR MOVE ZOEROES TO END IN JAVASCRIPT :- let j = -1; for (let i = 0; i < array.length; i++) { if (array[i] == 0 && j == -1) { j = i; } if (array[i] != 0 && j != -1) { swap(array, i, j); j++; } }
// right rotation by k places int k;// no of rotation cin>>k; int d = k%n; reverse(arr,arr+(n-d)); reverse(arr+(n-d),arr+n); reverse(arr,arr+n); for(int i: arr){ cout
code for right-rotation: void rotate(vector& nums, int k) { int n = nums.size(); if (k > n) { k = k % n; } reverse(nums.begin(), nums.begin()+n-k); reverse(nums.begin()+(n-k),nums.begin()+n ); reverse(nums.begin(), nums.begin()+n); }
Hii brother can you pls explain me why time complexity of intersection is O(1) and not O(n), where n is the size of larger sized array. Time stamp- 1:12:01
Thank you so much for taking out time of your busy schedule. Can you please make such videos on Trees as well ? That will be a great help. Thanks a lot😊😊
for right rotate:- just one line using inbuilt STL rotate(arr,arr+(n-k%n),arr+n); for Left rotate:- just one line using inbuilt STL rotate(arr,arr+k%n,arr+n);
I recommend everyone to solve the linked leetcode problems attached as well, as the code needs to be tweaked little bit . So u can understand and do by yourself Great approaches Striver. thanks
Let's march ahead, and create an unmatchable DSA course! ❤
Timestamps someone please :)
Use the problem links in the description.
At 23:47 my mind just got blown away. Me be like: - itna easy kese Benstocks 😂🙏. Bhai iPad ka notes ka bhi pdf dalo na . Tumaaher writing sei sab samajh mai ata hai. Boh tuf sight par itna bada article dekhne sei dar lagta hai 🙂. But you are doing amazing job bhai thank you 🙏😌.
appreciable !!
Please upload the next video.
@takeUforward
class Solution {
public:
void rotate(vector& nums, int k) {
int n = nums.size();
k =k%n;
int temp[k];
for (int i = n - k; i < n; i++)
{
temp[i - n + k] = nums[i];
}
for(int i=n-k-1;i>=0;i--)
{
nums[i+k]=nums[i];
}
for(int i=0;i
for moving zeroes to the end we cen write it in 1 loop instead of two though time complexity is same , complexity for understanding decreases : v oid moveZeroes(vector& nums) {
int j=0;
for(int i=0;i
Who is grinding their head with DSA in their summer vacation?? Heartly thanks to striver for making us understand dsa in such depth :)
Me😃
me too lol
bro this course from his website is completely free for now right ? ... or it has premium paid version as well ?
What do u mean by summer vacation 😢?
me first getting the optimal solution and then finding the brute 🤣🤣
mee too😂
#me2 moment
how to remember logic ,i always forget nd cant able to code
@@helloworld-n1z I am not the right person but still always go back to the code after a week or so and try solving it again. Then review it after a month. That is it, it will get hard coded in your brain after that.
Bro me too 😢
Isi wajah se easy problem solve krne me v time lgta h 😂😂 dimag me bs chlta h ki optimal hi krna h
Thanks a lot sir for taking out time from your busy schedule and making videos and uploading those videos in the span of 2-3 days. It takes a lot ot effort. Thanks a lot 😊😊
Timestamps:
0:00:00 - Intro
0:00:55 - Q1. Left rotate an array by 1 place
0:07:33 - Q2. Left rotate an array by D places
0:26:36 - Follow up Right rotate an array by D places
0:27:11 - Q3. Moving Zeroes to end
0:40:54 - Q4. Linear Search
0:43:01 - Q5. Union of Two Sorted Arrays
0:59:04 - Q6. Intersection of Two Sorted Arrays
1:12:22 - Outro
For Right Rotation of Array
void rotate(vector arr, int d)
{
if(d>size)
d = d % size;
reverse(arr.begin(),arr.end());
reverse(arr.begin()+d,arr.end());
reverse(arr.begin(),arr.begin()+d);
}
Guys i just wanna ask something....r u guys doing all these problems on your own or like just watching the lectures
First Understanding the problem then finding approach to solve it then if I make the correct solution then codding it in vs code and moving to nxt question and if I didn't get the solution then watching striver
27:00 rotating an array left by 1 place is equal to rotating it right by n-1 places. We can use this information for rotating an array to right by d places.
Perfect thought!
great
Bhai leetcode pa left rotation question reverse .end() and begin() use karna pad Raha hai but gfg ma nahi why
@@himanshukaushik9223 in case of vector we use stl function like begin() and end() but in case of array we don't use it for example in gfg
@@bhargavanand7325 thanks bro
I gonna fainted..after watching at last that this was easy section..what will happen god in future..bcz I m beginner and finding difficulties 😢😢
Me too bro similar situation 😢
Right Shift Solution(Leetcode 189):
k = k % arr.length;
reverse(arr, 0, arr.length-1-k);
reverse(arr, arr.length-1-k+1, arr.length-1);
reverse(arr, 0, arr.length-1);
Just do k=k%n, k=n-k!! as simple as that
Munnawar Faaroqi explaining dsa questions...😂😂😂😂😂
??
Aisa hai kaide me raho
@@DeepakKumar-e2s5q Ooye Chomu😂
tujhe pta to hai kya bolna chaha rha h tu
"THERE IS A ONLY ONE KING IN DSA"
not only your dsa knowledge is good also your communication skill, voice tone , body movement is superb 🥰🥰
✦
Learn left rotation of an array by one place
00:03
✦
Understand the difference between space used and extra space in algorithms.
06:07
✦
Learn how to left rotate an array in C++ or Java
18:42
✦
Left rotate an array by D places
24:15
✦
Use two pointer approach to move zeros to the end of an array.
34:25
✦
Summary of array problems
40:19
✦
Implementing a pointer approach to find the union of two sorted arrays.
50:18
✦
Union and intersection of sorted arrays
55:30
✦
Optimize time complexity using two pointer approach
1:06:02
✦
Optimal solution for intersection of two sorted arrays
Click to expand
1:11:14
One thing striver.....
In the sheet for the same question as we know there is a link attached for the gfg version and for the leetcode version but in some cases leetcode version is harder and sometimes gfg version.
So please pick the hard problem for that
Striver please bring string series. Much needed
Bro requesting you please upload videos alternatively as promised bcoz completely relaying on you for placements🥺🥺
Yes you are right, striver bro please we are requesting you please upload the video as promised by you 🙏
I am keeping my promise, if you see am covering 5 problems in one video. So recording such a long video, then editing it, then uploading it takes time. I can upload daily, if you want me to to cover one video.
@@takeUforward ok brother thanks for helping us .we are waiting for upcoming videos ☺️
True
@@takeUforward understood ur pain bro thanks for everything.
I did not only enjoy the lecture but loved it too. Thanks Striver Bhaiya for explaining so lucidly. ❤
Striver is the lion of this community
//HOMEWORK FOR ROTATE RIGHT
class Solution {
public:
void rotate(vector& nums, int k) {
k = k % (nums.size());
int n = nums.size();
vectortemp;
for(int i = n-k; i
Move zeroes question another approach with O(1) space
int j=0;
// Firstly taking all non- zeroes number
for(int i=0;i O(1)
Thank you brother if your infront of me i would have clean your feet with water 💦 because I ever seen tutor like you and your tutorials are more than a 10 lak rupees ❤❤❤
hahahaha
I always thought that the optimal solution to this code was the hashset one that you did in the middle part. It blew my mind when I saw the optimal one... And that too so easy man... Wow .. just wow to your observation ❤
Wrong Logic at 40:46 (Move Zeros to End ) what if the Array element is {1,0} at the first iteration your j=1 means you found zero element at index 1, Now you found first non zero element at 0 index you swap nums[i] and nums[j] now array look like this {0,1} and j is now 2 since i=1 means loop will run one more time bcz i is less than size of array i-e 2, Again you find non-zero element at index 1 i-e 1 you try to swap nums[1] and nums[2] You will end up with an Runtime error ArrayIndexOutOfBound.
thats why he took i=j+1
for the first time i guessed which concept can be used it might sound like a small thing but as a beginner who is just learning to code actually implementing codes without any reference and knowing which loop is used is really HUGE for me. THANK YOU SOO MUCH
same for me. feels like a big leap
hi in which question u implemented the code yourself? i am having a hard time in writing code for right rotate an arrray ky k places on my own...
bhaiya intersection of two array waale concept m jab aapne final arry nikala tab aapne 3 ko two time liya h but intersection mein toh common element aata h aur vo bhi one time hi aata h?
Hey Striver,
Won't this work fine for the Move Zero's to the end :
void moveZeroes(vector& nums) {
int i=0;
for(int j=0;j
How do you know if the first index i.e. i=0, will always going to be zero?
Also you cannot initiate j from 0, if arr[] = {1,2,3,0}, both I and j will point to 1 and since they both are non zero elements, you are swapping them with themselves only.
in ques rotating arr by k places last for loop n-d = 6-3 =3 but ath 43 index there is alreeady 7 .
Your course is awesome wish I could have found your course a year before currently I am in 3rd year of my clg 😊
From which college u r
@@anshu59kumari Techno International New Town West Bengal
Bhiya arrays k dsa m list kaa zikrr kyu krna, list have method to add but arrays don't have.. I know you are well versed in your profession but ek dikkat h beginners ko hoti h when they heard About list and trying to implement it in arrays😢, just my point of view hope you understand
Understood and what an explanation
Love your explanation bro, just continue doing what you are doing for the coding community
Amazing person
GUYS THIS MY BRUTE FORCE APPROACH PLEASE TELL ME IS RIGHT OR WRONG 🙏🙏🙏
import java.util.ArrayList;
public class Step3_Arrays {
static void EndZeros(int []arr,int n){
ArrayList TempArraylist1=new ArrayList();
ArrayList TempArraylist2=new ArrayList();
for(int i=0;i
Why bro Why, Brute force->better-> optimal, Its really a big effort. thanks for such wonderful video series. Love the way u explain.
wrong code for intersection of two arrays will not work in leetcode
What a wonderful video, it was vey good. Your way of teaching concepts through questions is best.
i think i got a better solution for move zeroes to end, If im wrong please correct me
void Solve2(int arr[] , int arrl) //O(n) with space complexity O(1) {Only 1 variable }
{
int counter =0;
for(int i=0;i
Thank you for all the tutorials,
Please keep supporting from starting to get good placement by the help of your tutorials!
class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length;
k=k%n;
reverse(nums,n-k,n-1);
reverse(nums,0,n-k-1);
reverse(nums,0,n-1);
}
void reverse(int arr[],int start,int end)
{
while(start
0:00 Introduction of course
01:01 Left rotate an Array by 1 Place
04:38 Pseudo code
07:17 Code-compiler
08:05 Left rotate an Array by D Places
14:38 Pseudo code
20:18 Code-compiler
27:13 Move zeroes to end
37:41 Pseudo code
40:30 Code-compiler
41:05 Linear search
42:01 Pseudo code
42:43 Code-compiler
43:04 Union of two sorted array
53:33 Code-compiler
59:05 Intersection of two sorted array
1:09:30 Code-compiler
Thank you Paras!
@@takeUforward Welcome and thanks for this amazing course.
void reverse(int arr[],int start,int end){
int temp;
while(start
Salute to this consistency.
😆😆
@@rohandhalpe9084 😡😡😡
@@saurabhtiwari9614 kya hua bhai 😔
@@rohandhalpe9084 Bhai aaisa face kyo bnaya h.
Great! btw in the worst case of Intersection, the space complexity would be O(n1>n2?n2:n1) because whichever one is smaller matches completely with the other array and ends. P.S.- the space is for returning the answer and not solution.
Understood 😄.
Logic used for right rotate the array k places is that instead of rotating array right by k places I have rotated it n-k places to left .
so code for this is -
class Solution {
public:
void rotate(vector& nums, int k) {
int n = nums.size();
k = k % n;
reverse(nums.begin(),nums.begin()+(n-k));
reverse(nums.begin()+(n-k),nums.end());
reverse(nums.begin(),nums.end());
}
};
hey, me also applied same approach
same here
Exactly right
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
u can do this also.
right rotate
any index i with d right rotation then new index will be
(i+d)%n where n is the length of an array
Thank You Striver for such an effort.
Your explanations and teaching is really amazing.
Its really Valuable /priceless content :)
why my output is not coming?????
349. Intersection of Two Arrays
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
int i=0;
int j=0;
int n1=nums1.size();
int n2=nums2.size();
vector ans;
while(i
In the brute force approach of union of arrays, you could have directly returned the set instead of taking a temp vector and copying it all over, because the set would only take the single copies of the elements are the time of insertion
bro you are right but most of the time they i.e., dsa practicing websites expect you to return the result in the form of array(for c++ vector and for Java ArrayList).
how about using recursion for left rotation at 0:24:00 ???
void left_rotate_better(int arr[],int n,int d)
{
d=d%n;
if(d==0)
return;
int temp=arr[0];
for(int i=1;i
This much consistency is all we needed bhaiya🤞🤞🤞kudos to you
it took me an hour to do rotate by K problem now even i don't remember how i did this
```js
function a(len,jk){
if(jk >= 0) return jk
if(jk < 0){
const b = len - Math.abs(jk)
return a(len, b)
}
}
var rotate = function(nums, k) {
const copyArr = [...nums]
for(let j = 0; j < nums.length; j++){
const replacement = a(nums.length, j-k)
nums[j] = copyArr[replacement]
}
return nums
};
~```
Actually, there is another optimal solution for moving zeroes problem. It is similar to the function we use in quicksort algorithm (quickselect part for arranging elements around pivot).
void Optimal2(̀vector& nums) {
int j=-1, n=nums.size();
for(int i=0; i
Exceptionally concise👏
can u explain how the swap function works here. we want to move all the zeroes in the end how nums[++j]; ????
u wanna see my solution??
void Zero_at_last(int arr[], int n){
int i=0;
for (int j = 1; j < n; j++)
{
if(arr[i]==0 ){
if(arr[j]==0){
continue;
}
swap(arr[i], arr[j]);
}
i++;
// cout
Assignment:-
"Right rotate an array by k places"
class Solution {
public void rotate(int[] nums, int k) {
int[] ans = new int[nums.length];
for(int i = 0; i < nums.length; i++){
ans[(i+k) % nums.length] = nums[i];
}
for(int i = 0; i < nums.length; i++){
nums[i] = ans[i];
}
}
}
Hey striver wonderful video. I have a query. The code will be applicable only if the vector or array is sorted in the intersection part. So do we need to sort it again or is there any other optimal approach ?
class Solution {
public void rotate(int[] nums, int d) {
int n=nums.length;
d=d%n;
int l=0,r=n-d-1;
for(int i=0;i
bhai ki pehli video lgayi h ye mene. bohut maja aya, dil garden garden hogya bilkul. thanku bhai.😁
Simple code for right rotating an array (Python):
new_arr = [1,2,3,4,5,6,7]
d = 22
n = len(new_arr)
d = d%size
left_arr = new_arr[n-d:]
right_arr = new_arr[:n-d]
new_arr = left_arr + right_arr
Thank you so much for sharing the content free of cost!! very nicely explained too😘
26:02 here the time complexity is 0(N);not O(2N)
In reverse
The time complexity is n/2;
Not 0(N);
Correct me if I am wrong
Hi Striver can you please please upload the notes which you are explaining it will be very helpful 🙏🙏
Take your own notes
conscise solution for move zeroes to end
class Solution {
public:
void moveZeroes(vector& nums) {
int n = nums.size();
int j = 0;
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {
swap(nums[i], nums[j]);
j++;
}
}
}
};
Bhaiya kab tk poora hoga 🥲
In a previous post bhaiya said that he will try to cover this course in the next 3 months.
For the instersection question,why don't you consider temp array/vector space in addition to visted array for space complexity(brute force) ,because that too is used?.And for the optimal solution space complexity must be O(min(n1,n2)) if all elements are common??...
Right rotate array by d places is equivalent to left rotate array by n-d places.
void rightRotateArrayOptimal(int arr[],int n,int d){
d = d%n;
d = n-d;
reverse(arr,arr+d);
reverse(arr+d,arr+n);
reverse(arr,arr+n);
}
It's wrong it should be
d=n%d
reverse(a,a+n)
reverse (a,a+n-d)
reverse (a+n-d,a+n)
move all zeroes to end of array this is same approch but some lines of code are different from that of strivers!!!!!
void pushZerosToEnd(int arr[], int n)
{
// code here
int i=0;
int j=i+1;
while(j
😢sir, you are solving each problem with vectors or stack,,
As we are doing array problems,,,
So, solve it using array na
got confused with move zero to end problem
easy solution
class Solution{
public:
void pushZerosToEnd(int arr[], int n) {
// code here
int i=0,j=0;
//int size=n;
while( i
Bhaiyaa ji please upload videos as fast as possible .Our placement season starting soon in June.💫💫💫💫💫💫💫💫💫💫💫💫💫💫
last question optimal solution was so cute. Even cuter than my imaginary girlfriend. Just the difference is I can't understand her.
🤣🤣🤣
Space complexity of Intersection problem would be O(min(n,m)) for optimal solution
Brute Force Solution :
TC : O(n) + O( n-arr.size() ) = O( 2n - arr.size() );
SC : O(n);
#include
vector moveZeros(int n, vector a) {
// Write your code here.
vectorarr(0,n);
for(int i=0;i
RIGHT ROTATE BY K PLACES
class Solution {
public void rot(int[] arr, int s, int e){
while(s
why am I getting the 'this is taking too long' for the intersection problem using the first approach? can you please explain?
#include
vector findArrayIntersection(vector &arr1, int n, vector &arr2, int m)
{
vector visited(m,0);
vector arr;
for(int i=0;i
How to know our solution is otiomal solution or better solution
We have to memorize optimal solution or what!!?
at 16:40 the i=k striver had taken should be n-d right as k is not defined or we can use n-d in k
For the last question, I got the optimal solution before brute force approach :/
In move zeroes to end problem we can use this also...,
int y=0;
for(int i=0;i
sir u write code and the code runs in one go are u hacker or wottt
🎯 Key Takeaways for quick navigation:
00:56 🔄 *Left rotate an array by one place involves moving elements one place ahead. Optimal solution involves in-place rotation without using a new array.*
05:26 ⏰ *Time complexity of left rotation by D places is O(N+D). Extra space complexity is O(D) due to the use of a temporary array.*
12:20 🤔 *When left rotating an array by D places, D can be reduced to D mod N, as multiples of N rotations bring the array back to its original state.*
20:37 ⚙️ *Optimal solution avoids using extra space by reversing the array elements in three steps: reverse the whole array, reverse the first D elements, and reverse the remaining N-D elements.*
23:04 🔄 *The speaker explains a method to rotate an array to the left by a given number of places using three reverse operations.*
27:12 🔄 *The problem of moving zeros to the end of an array is introduced, and a Brute Force approach is discussed, involving identifying non-zero numbers, moving them to the front, and filling the remaining positions with zeros.*
33:45 🔄 *An optimal solution for moving zeros to the end is presented, using a two-pointer approach to efficiently move non-zero elements to the front while iterating through the array.*
40:57 🧐 *Linear search is introduced as the problem of finding the first occurrence of a given number in a sorted array. The speaker presents a Brute Force approach involving iterating through the array and checking for equality.*
43:04 🧑🤝🧑 *The problem of finding the union of two sorted arrays is discussed, emphasizing the need for an optimal solution. The speaker starts with a Brute Force approach involving combining both arrays and removing duplicates.*
44:40 🧭 *Brute force approach for finding the union of two sorted arrays involves using a set data structure to ensure uniqueness and sorted order.*
50:22 🚥 *Optimal approach for finding the union of two sorted arrays uses a two-pointer approach to efficiently iterate through both arrays, considering unique elements.*
53:39 🕰️ *The time complexity of the optimal approach for finding the union is O(N1 + N2), where N1 and N2 are the sizes of the two arrays.*
59:00 🤝 *Brute force approach for finding the intersection of two sorted arrays involves checking for corresponding elements and using a visited array to ensure uniqueness.*
01:05:59 🔄 *The time complexity of the brute force approach for finding the intersection is O(N1 * N2), where N1 and N2 are the sizes of the two arrays.*
01:06:13 🧠 *Brute Force approach for array intersection involves checking every element in both arrays for a match, leading to a time complexity of O(N1 * N2).*
01:07:32 🔄 *Optimal solution for intersection utilizes a two-pointer approach due to sorted arrays, resulting in a time complexity of O(N1 + N2) and no extra space usage.*
01:09:48 🤖 *Implementing the optimal solution involves iterating through both arrays, comparing elements, and building the intersection array with minimal space complexity.*
Made with HARPA AI
Bro please add Java code in side while you are writing c++ code.
In MAANG interview generally the coding round is of 45 min and they ask 2-3 LC medium questions.So, approx. 15 min(discuss + solve) for 1 question if 2 medium LC question they asked. So, if we know optimal solution then discussing on brute force approach will cost us. So, any suggestion here ?
//RIGHT ROTATE
class Solution {
public:
void reverse(vector &nums,int start,int end){
while(start
he never skips anything, Patience is next level!!
right rotate array k places
brute and optimal approach
class Solution {
public:
void rotate(vector& nums, int k) {
// brute force approach
// int n = nums.size();
// k = k % n;
// int temp[n];
// for(int i = n - k; i < n; i++) {
// temp[i - (n - k)] = nums[i];
// }
// for(int i = n - k - 1; i >= 0; i--) {
// nums[i + k] = nums[i];
// }
// for(int i = 0; i < k; i++) {
// nums[i] = temp[i];
// }
// optimal approach
k=k%nums.size();
reverse(nums.begin(),nums.begin()+(nums.size()-k));
reverse(nums.begin()+(nums.size()-k),nums.end());
reverse(nums.begin(),nums.end());
}
};
In the three reversals, we are doing iterations just for half the time i.e O(d/2) + O((n-d)/2) + O (n/2) making it O(n) so TC as well as SC of optimal solution is better than the better solution.
class Solution {
public:
void rotate(vector& nums, int k) {
k=k % nums.size();
vector temp(nums.size());
for(int i=0;i
left rotate without extra space:
i=0
for j in range(1,n):
arr[i],arr[j]=arr[j],arr[i]
i+=1
return arr
Rotate right ---->>>>
void rotate(vector& nums, int k) {
vector temp(nums.size());
for(int i=0; i< nums.size(); i++)
{
temp[(i+k)%nums.size()] = nums[i];
}
nums=temp;
}
in the brute force solution of the interscetion of two array , the code will be correct even if i dont use break statement , only the number of iterations will increase , but in the given problem link , its not showing the correct answer in that case (if i am not using the break case)
left rotation to right rotation: simple approach is to think oppositely to left rotation.
Shift all elements right of d and add to temp and push it.
Just reverse the order of the reverse statements used in left rotation!.
Understood but, 1:10:36 was 💀, no offence striver bhaiya
😢
I have written this approach for rotating the array to the right by k steps : void rotate(vector& nums, int k) {
k%=nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin()+k, nums.end());
}
OPTIMAL CODE FOR MOVE ZOEROES TO END IN JAVASCRIPT :- let j = -1;
for (let i = 0; i < array.length; i++) {
if (array[i] == 0 && j == -1) {
j = i;
}
if (array[i] != 0 && j != -1) {
swap(array, i, j);
j++;
}
}
// right rotation by k places
int k;// no of rotation
cin>>k;
int d = k%n;
reverse(arr,arr+(n-d));
reverse(arr+(n-d),arr+n);
reverse(arr,arr+n);
for(int i: arr){
cout
code for right-rotation:
void rotate(vector& nums, int k) {
int n = nums.size();
if (k > n) {
k = k % n;
}
reverse(nums.begin(), nums.begin()+n-k);
reverse(nums.begin()+(n-k),nums.begin()+n );
reverse(nums.begin(), nums.begin()+n);
}
Hii brother can you pls explain me why time complexity of intersection is O(1) and not O(n), where n is the size of larger sized array. Time stamp- 1:12:01
Thank you so much for taking out time of your busy schedule. Can you please make such videos on Trees as well ? That will be a great help. Thanks a lot😊😊
two pointer approach is great ...
for right rotate:- just one line using inbuilt STL
rotate(arr,arr+(n-k%n),arr+n);
for Left rotate:- just one line using inbuilt STL
rotate(arr,arr+k%n,arr+n);
void right_rotate(int arr[],int n,int d){
reverse(arr,arr+n-d);
reverse(arr+n-d,arr+n);
reverse(arr,arr+n);
}
I recommend everyone to solve the linked leetcode problems attached as well, as the code needs to be tweaked little bit . So u can understand and do by yourself
Great approaches Striver. thanks
understood😊
union of 2 arrays can also be done without using extra space