14. Arrays (hard)

1. Pascal's Triangle-


---------------------------------------------------------------------------------------------------------------------------

Variety-1: Find elmt in rth row & cth column in pascal triangle (r,c as per 1 based indexing)

Soln:         time- O(r)      space- O(1)

We calculate: 
(r-1)C(c-1)

--------------------------------------------------------------------------------------------------------------------------

Variety-2: Find row 'r' of pascal triangle

Brute:        time: O(r^2)    space: O(1)

We do a loop and find all elements of the given row
     

   
-----------------------------------------------
Better:         time: O(r)     space: O(1)



-----------------------------------------------------------------------------------------------------------------------------
Variety-3: Print first 'n' rows of pascal triangle

Brute:    time- O(r^3)
----------------------------------------------------------
Better:    time: O(r^2)
---------------------------------------------------------------------------------------------------------------
NOTE-
1. There is atmost 1 element in an array with frequency > n/2
2. There are atmost 2 elements in an array with frequency > n/3
---------------
3. Brute: 
    Two sum:   2 loops- fix one     element and find other:  O(n^2)
    Three sum: 3 loops- fix two   elements and find other:  O(n^3)
    Four sum:   4 loops- fix three elements and find other: O(n^4)
--------------
4. Optimal: we reduce one loop from each using some optimisation 
    Two sum:   O(n):     use hash map / sorting + 2 pointer
    Three sum: O(n^2): use hash set  /  sorting + 3 pointer
    Four sum:   O(n^3): 
--------------------------------------------------------------------------------------------------------------------------
2. Majority Elements (> floor(n/3))
print all of them.
-------------------------------------------------
Brute- time: O(n^2)
there will be max 2 such elmts⭐
--------------------------------------------------------------
Better-  time: O(n)          space: O(n)

using map
we can further optimise this solution from two pass to single pass
we will only add an element in ans when its freq equals 1 + (n/3), kyuki >n/3 mein toh vo element repeatedly add ho jayega fir toh
-----------------------------------------------------------
Optimal-   time: O(n)    space: O(1)

Extended Moore Voting Algorithm


---------------------------------------------------------------------------------------------------------------------------
3. Three Sum-
                                        find all UNIQUE triplets which add upto 0
------------------------------------------------
to store only unique triplets we do this:
1. instead of directly storing them we first store all of them in a set
2. before inserting any triplet in a set, we sort the triplet, so all triplets are on same page
-------------------------------------------------
Brute-   time: O[(n^3)*(logm)]          space: O(m)
                            where m = no.of triplets

use 3 loops and check all possible combinations 

------------------------------------------------------------------------------------
Better-     time: O[(n^2)*logm]           space: O(n+m)
                           where m = no. of triplets

use set to find 3rd element in constant time



----------------------------------------------------------------------------------
Optimal-     time: O(NlogN + N^2)        space- O(1+m) 
where m = no. of triplets

use, sorting + 3 pointers
IMP- handling duplicates...

-------------------------------------------------------------------------------------------------------------------------
4. Four Sum-
Find all unique Quads that add up to a target value

Brute- time: O(N^4)
use 4 loops 
----------------------------
Better- time: O(N^3)*logM 

use hash set for finding 4th element

---------------------------------------------------
Optimal- time: O(N^3)

sorting + 4 pointers
fix 2 and move the other 2

-----------------------------------------------------------------------------------------------------------
5. Length of Largest subarray with 0 sum⭐

use hashing + prefix sum:
Same prefix sum appearing twice means the subarray between them has sum zero
if sum till index=j is X and sum till index=i is X
then sum from j+1 till i is 0
as it means we are adding 0 to X thus getting X
here, j is mpp[sum] and i is i

hence, length is [ i-(mpp[sum]+1)+1 ]

Also, if we get 0 sum instead of a non-zero sum, at any index, then we can directly store length of this subarray.

---------------------------------------------------------------------------------------------------
6. Count Subarrays With Xor K:

Brute-  time: O(n^2) 
we will check all possible subarrays using 2 loops

------------------------------------------------------
Optimal- time: O(n)    space: O(n)⭐

hashmap + prefix XOR

remember base case of mpp[0]=1

-------------------------------------------------------------------------------------------------------------------------
7. Merge overlapping intervals-

Brute-     time: O(n^2 + NlogN)   space: O(1)

Sort the intervals and then,
for every interval check all intervals which can overlap with it

-------------------------------------------------------
Optimal-  time: O(NlogN + N)   space: O(1)

 using Sorting 

1. sort the intervals array as per start time
2. now keep extending the last interval in answer array, while overlap exists. Else, start a new interval.

The condition to extend is ( current interval's start time >= prev interval start time )   &&
                                           (   ,,          ,,           ,,        ,,   <= prev interval end time )
but since we sorted the intervals, hence only one condition is enough to be checked.

----------------------------------------------------------------------------------------------------------------------------
8. Merge 2 Sorted Arrays
(w/o Extra Space)+(one of the arrays has buffer space)

Brute:  time:O(klogk)  space:O(1)
            where, k=m+n
1. put all elements of v2 in 0s of v1
2. sort v1

----------------------------------------------------
Optimal:   time: O(m+n)   space:O(1)

it is somewhat merge step of merge sort algorithm...
using 3 pointers from the back
--------------------------------------------------------------------------------------------------------------------------
8.2 Merge 2 Sorted Arrays⭐
(w/o Extra Space)+(NO buffer space)
------------------------------------
Brute-                    time: O(n+m)     space:O(n+m)

1. use two pointers to store all sorted elements in a temp array
2. now from temp array choose first m elements and overwrite the array 1 & choose next n elements and overwrite array 2

---------------------------------
Optimal-1:            time: O( min(m,n) + nlogn + mlogm )     space: O(1)

we will use 2 pointers, one at largest element of array 1 and other at smallest element of array 2. Now, just sort the individual arrays.

---------------------------------------------
Optimal-2
: ⭐⭐

using Shell Sort (gap method)

initial gap = ceil((m+n)/2)
every later gap = ceil(gap/2)

this is simulated as:   ceil(x/2) = (x/2) + (x%2)


-----------------------------------------------------------------------------------------------------------------------------
9. Find Repeating & Missing Number-

given array contains numbers from 1 to n
one number is missing and one number occur twice. Find the two numbers
--------------------------------------------------------

Brute
-    time: O(n^2)       space: O(1)

we will use 2 loops and do a linear search for every number from 1 to n to check frequency of each number

also, we can have a sorting based solution as well
--------------------------------------------------------------
Better-    time: O(n)      space: O(n)

use a hash array storing frequencies of each element of array & see

----------------------------------------------------------------

Optimal-1:   time: O(n)    space: O(1)⭐

using MATHS

X = repeating    &   Y= missing
(X-Y)              =   (S = sum of array elements)          -  (Sn = sum from 1 to n )           
(X^2) - (Y^2) =   (sum of square of array elements)  - (sum of squares from 1 to n
find X and Y✅
------------------------------------------------------------------------
Optimal-2:     time: O(n)    space: O(1)    (Not - Intuitive & not for interview)

using bit manipulation

XOR cancels all correct numbers, only the missing and repeating remain, and we separate them using a differing bit.

1. xor all array elements and numbers from 1 to n, to get a^b
2. find rightmost set bit in a^b, which is differing bit in both numbers
3. separate array elements into two clubs: one having this bit posn as 0 and other having 1
4. similarly do for all numbers from 1 to n.
5. now take xor of all numbers in one club => we get a number
6. now take xor of all numbers in zero club => we get another reqd number
7. now iterate in array to check which number occurs twice and print in reqd order the two numbers



--------------------------------------------------------------------------------------------------------------------------
10. Count Inversions-⭐
-----------------------------------------------------------------
Brute- time : O(n^2)
Using 2 loops we will count for every element how many inversions exist.

-----------------------------------------------------------
Optimal-  time: O(nlogn)  space: O(n)

divide & conquer algorithm
merge sort mein ek cnt variable banalo aur har baar jab dono sorted arrays ko merge krte hain toh us step pe cnt krlo kitne inversions hain.


-----------------------------------------------------------------------------------------------------------------------
11. Reverse Pairs-

Brute-        time: O(n^2)      space: O(1)

using 2 loops, we will check each combination

------------------------------------------------------
Optimal-    time:(nlogn)     space: O(n)

using divide & conquer

we will add a new step before merge step in merge sort.
This step would count all reverse pairs in the two sorted arrays before they get merged.
---------
Unlike inversion problem, here it is NOT the case that, if an element on left is NOT forming a valid pair on right , then others on the left would also NOT form valid pair.
As here condition is different : (left > 2*right)
So, here we will see for every element in left array, ki right mein kon konse valid pair ban rhe hain har left ke element ke liye. 
Also, while checking every element in left, we do not reset right pointer, as valid pairs keep repeating in next elements of left, so increased length le lenge har baar...
--------


-----------------------------------------------------------------------------------------------------------------------------
12. Maximum Product Subarray-⭐⭐

Brute
-         time: O(n^2)

check all possible combinations
------------------------------------------

Optimal-1:   time: O(n)

Using prefix suffix products
There are 4 cases:
1. array contains all positives => whole array product is answer
2. array contains even negatives => whole array product is answer
3. array contains odd negatives => either remove prefix before 1st negative or suffix after last negative
4. array contains zeros => partitions ka dekho in between zeros
---------------
we maintain products from front and end of array, hence case 1,2 handled.
zero aate hi product reset ho jayega, hence case 4 handled.

-------------------------------------------------------------------
Optimal-2:    time: O(n)

Using DP / modified Kadane

At each index i, for best subarray product we: either choose current element to be included in best subarray product till (i-1) or, start fresh subarray product from index i.
But due to negative numbers, we will also maintain minimum products,
as if v[i] < 0, then: minimum product till i-1 now if multiplied with curr becomes max product.
-----------
instead of: maxi = max( v[i], maxi*v[i] , mini*v[i] )
            & : mini = min ( 
v[i], maxi*v[i] , mini*v[i] )
we swap maxi & mini if, v[i] < 0
-----------
----------------------------------------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

30.) DP on subsequences

19. Strings (LB)

32. Binary Trees-2 (bfs/dfs med problems)