13. arrays medium
Priority-wise
- Two sum problem✅
- sort arr of 0s, 1s, 2s✅ DNF
- majority elmt✅ Moore voting algo
- max subarray sum✅ Kadane algo
- buy & sell stocks✅
- Next permutation🔥
- Longest consecutive seq🔥
- Rotate matrix by 90 CW✅
- Count subarrays with sum k🔥
- Rearrange the array in alternating + & - items✅
- Set matrix rows& cols to 0s for zero elmt✅
- Spiral matrix✅
- Leaders in an array✅
2 sum problem-
return index of 2 elmts in array which adds up to equal the target sum
Brute- O(N^2)
----------------------------------------------------------------------------------------------------------------------------
Sort an array of 0s, 1s, 2s-
Brute- (NlogN) sort
Better-(2N, with no extra space) cnt no of 0,1,2 and overwrite using loops
Optimal-(N)
DNF Algo-(dutch national flag)
3 pointer
-----------------------------------------------------------------------------------------------------------
Majority-elmt ( >floor(n/2) times in array)Brute-
searching- (time- n^2)
Better-
1. map- (time-nlogn & space-n)
2. sort and cnt-(time- nlogn & space-1)
Optimal- O(n)
(Moore Voting Algo)
---------------------------------------------------------------------------------------------------------------------------
Maximum subarray sum-
Better- O(N^2)
If the sum of elements before a subarray is positive, we say we’ll include them in the subarray and if the sum is negative, we’ll exclude them
print subarray having maximum sum-
---------------------------------------------------------------------------------------------------------------Buy And Sell Stocks-
sell on i-th day and buy on min of 0 to (i-1)th day...
imagine each day as selling day and uske piche ke sabhi dino me se min choose krke usko buying day banake dekhlo konse elmt ke corr max profit aara
----------------------------------------------------------------------------------------------------------------------------
Alternate +ve and -ve in array-
[no.(+) = no.(-)ves in array]
BRUTE simple, use 2 arrays to store +ves and -ves and then update original array
time: O(2N), space- O(N)
OPTIMAL time: O(N), space- O(N)
---------------------------------------------------------------------------------------------------------------------------
Alternate +ve & -ve
no.(+) != no.(-) array🔥
time- O(2N) space-O(N)
last me bache kuche ko same order m simply append krdo
Next Permutation-
if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container.
----------------------------------------------
BRUTE- O(n*n!) 😕
Step 1- generate all permutations using recursion
Step 2- linear search of given
Step 3- find next permutation
------------------------------------------------
------------------------------------------------
BETTER- O(n)
use in-built fn.
next_permutation(v.begin(),v.end()); // it automatically generates next permutation and updates v
------------------------------------------------
OPTIMAL- O(3n) 🔥🔥
we will implement that in-built fn ourselves-
out of all possibilities we will try combinations for those only jisme ek position pe jo digit hai toh us digit ke right ki saari digits me koi ek digit current digit se badi hai, e.g., 125430 mein 1 ke baad se hi next bigger permutation ban sakti hai...kyuki 2 ke right me hi 2 se bade digits hai aur 5 ya 4 ya 3 ke right mein inse bade digits nhi hain...
1. toh right se left tak breakpoint dhundo ki kab a[i] chota hora a[i+1] se...
2. next permutation k liye breakpoint ke right ke sab digits m bhi right se start kro dhundna ki sabse pehla digit konsa hai breakpoint wale digit se bada
3. bache hue digits ko new permutation mein sorted order m daaldo...
-----------------------------------------------------------------------------------------------------------------------------Leaders in an Array-
simple
BRUTE- linear search for each element, ki uske aage ke saare chote hain usse ya nhi- O(N^2)
OPTIMAL- piche se loop chalado max ka var banake dekhte raho
-----------------------------------------------------------------------------------------------------------------------------
Longest Consecutive Sequence-
return length of longest consecutive elmts sequence which can be formed out of given unsorted array
Brute- O(N^3)
linear search for x+1 for every x and then inc count and update maxi variable
Better- O(N+NlogN)
sort the array & then count for consecutive possible elmts & update maxi ,
considering n=0 & same element ke cases.
" bich ke badle start wale pkdo "
make unordered set & check if a[i]-1 exists for a[i] ...
if do not exist, then a[i] can be starting elmt so see if a[i]+1, a[i]+2 and so on...exists, then correspondingly update maxlen
if exists, then skip this iteration kyuki bich me se ni dekhna
similarly, check for rest of the elements...
-------------------------------------------------------------------------------------------------------------------------
2D MATRIX-
It is a vector of vectors
It is dynamically resizable in both dimensions. e.g.,
vector <vector<int>> mat;
no.(rows) = mat.size();
no.(cols) = mat[0].size();
vector<vector<int>> v(rows, vector<int>(cols, el));
vector<vector<int>> v = { {1, 2, 3},{4, 5, 6} }; 2 rows
----------------------------------------------------------------------------------------------------------------------------
SET MATRIX 0'S-
if an elmt=0 then set full row & col to 0s
Brute- O(nm^3)
jis posn pe 0s the initially us posn ke corr row & col ke
(non 0 & non -1 elmts) ko -1 kardo
baad mein poore matrix mein jaha jaha -1 hai waha waha 0 banado
fir ek baar aur traverse kro and jis element ke corresponding i or j me se ek mein bhi cnt 1 tha us element ko 0 banado.
Optimal- 🔥🔥
1.) instead of creating another 2 arrays , given matrix ki hi first row & col ko edit krdo like inme ek elmt ko 0 bnado agar niche wale corr row or col ke elmts me se koi 0 hai.
2. ) DO NOT TOUCH FIRST ROW, COL WALE AT THIS STEP . then ye sab ke baad 1st row, col ko chhodke baakiyo ko dekho ki har elmt k liye kya 1st row,col me corr 0 hai toh us elmt ko 0 bnado aur elmt elmt krke entire row,col jisko bnana tha 0 usko bnado.
3.) now for 1st row, col elmts we will start from row not col else order hampered. like a14 if anyone out of a14 itself or a11 is 0 then we transform a14 to 0 and now do similarly for other remaining.
---------------------------------------------------------------------------------------------------------------------------
ROTATE MATRIX BY 90DEG CW-
BRUTE- O(n^2), space- o(n^2)
create new matrix
new ka last col is purane ki 1st row,
new ka 2nd last col is purane ki 2nd row , & so on...
OPTIMAL- O(n^2) space- O(1)
transpose krke har row ko reverse krdo.
[ PS- transpose ke liye non diagonals ko swap (like a01 with a10) ]
---------------------------------------------------------------------------------------------------------------SPIRAL MATRIX-
time- n^2, space- n^2.
given a matrix print it in spiral order in a vector
use 4 variables top, bottom, left, right.
There are 4 operations in cycles- L to R, T to B, R to L, B to T.
---------------------------------------------------------------------------------------------------------------
Count no. of Subarrays with given sum :

















Comments
Post a Comment