12. arrays easy
Array contains elements with similar data types
int arr[n]==> garbage values if inside main
==> 0s if globally.
--------------------------------------------------------------------------------
- rotate✅
- intersection🔥
- all zeros to end✅
- missing number✅
- number appears once✅
- longest subarray with sum k🔥
- Largest, 2nd largest✅
- remove duplicates✅
- union✅
- max consecutive 1s✅
- sorted check✅
LARGEST
Ans- (for positive elements)
BRUTE(nlogn)- sort it and then do as asked
OPTIMAL(n)-use loops
---------------------------------------------------------------------------------
2nd LARGEST
Ans-(for positive elements)
BRUTE- sort wala with duplicate in consideration
BETTER- 2 loops with ,, ,, ,,
OPTIMAL-single loop with 2 if conditions
----------------
Take 2nd largest as -1(all +ve elements) or, INT_MIN(-ve also)
Take 2nd smallest as INT_MAX;
-----------------------------------------------------------------------------------
Check array sorted or not
check if, ( nxt elmt >= prvs ) or not
-----------------------------------------------------------------------------------
Remove duplicates from array (in place)
BRUTE(NlogN)- array se set mein daal aur fir set se array mein...
Left Rotate by one place-
[1,2,3,4,5]----->[2,3,4,5,1]
----------------------------------------------------------------------
Left rotate by k-places:
BRUTE -
temp array mein first k elmts daaldo
baakiyo ki shifting krdo piche
unke aage temp wale bhardo.
---------------------------------------------
Right Rotate By k-places
BRUTE- O(kn) or u can also do in n+k approach
1. BRUTE - time-O(N), space-O(N)
put all non-0 elmts into temp array
replace all starting elmts of array with temp wale & later wale as 0s.
2. OPTIMAL - time- O(N), space-O(1)
-----------------------------------------------------------------------------
Union of 2 sorted arrays-
do not repeat any element
using sets
for unsorted arrays also
----------------------------------------------------------------------------
Intersection of 2 Sorted Arrays-
OPTIMAL- O(n1+n2) space-O(1)
(2 pointer)
3. OPTIMAL-
so better code for both (0s & +ves) OR optimal for +ve, -ve, 0s -->
just update the map with the sum only if that sum was not there in the map prvsly...
OPTIMAL- time- O(2N), space-O(1)
2 pointer approach
for positives only
Comments
Post a Comment