12. Arrays (easy)
int arr[n]==> garbage values if inside main
==> 0s if globally initialised
-------------------------------------------------------------------------------------------------------------
1. Remove duplicates from Sorted array:
Push all unique numbers at start and whatever at the end of uniques....
Brute :(nlogn)
array se set mein daal aur fir set se array mein...
2 pointer approach
[1,2,3,4,5]----->[2,3,4,5,1]
----------------------------------------------------------------------------------------------------------------------------
3. Left rotate by k-places:
Brute- time: O(nk)
rotate by 1 place wale code ko K times loop mein chalado.
-----------------------
Better- time: O(n+k) space: O(k)
Using an extra helper array.
Brute- time: O(N) space-O(N)
Using a temp array.
- put all non-zero elements into temp array & replace all starting elmts of og array with temp wale & later wale with 0s
Using 2 pointer :
first 0 elmt pe j aur uske aage i set krke dekhte raho
if v[i] is non zero then swap it with v[j] and increment j then...
6. Union of two Sorted arrays containing duplicates
----------------
Store elements from both arrays in an ordered set.
6. Intersection of two Sorted Arrays containing duplicates
But maintain a visited array for v2, so we can handle duplicates.
Optimal- time: O(n1+n2) space: O(1)
2 pointer
Optimal: single pass using a counter
Even a similar approach with a 2 pointer can also be used :
---------------------------------------------------------------------------------------------------------------
using linear search
for every element, we search corresponding pair in array & whichever element occurs only once in the array is our answer.
Better- time: O(n) space:O(n)
we prefer unordered map
Optimal- time: O(n) space: O(1)
using XOR property
use 2 nested loops
Using mapping & prefix sum
(optimal for array containing positives & negatives)
Prefer unordered map
1. we store in a map, index vs sum of elements till that index
2. then we iterate on the array and if at an index sum is X and there exists a sum of X-k before that, then we can say we found a subarray with sum K
Below code is for single pass, we can instead do it in two pass also, where firstly we store all sums as key and indices as values & in second pass we perform searching for x-k sum
For longest subarray, we prefer x-k as left as possible, So we update the map with the sum only if that sum was not present in the map.
Optimal- time: O(n) space: O(1)
Sliding window approach
Optimal for array containing only positives
----------------------------------------------------------------------------------------------------------
Comments
Post a Comment