13. Arrays (medium)

  1. buy & sell stocks✅
  2. Next permutation🔥
  3. Longest consecutive seq🔥
  4. Rotate matrix by 90 CW✅
  5. Count subarrays with sum k🔥
    1. Rearrange the array in alternating + & - items
    2. Set matrix rows & cols to 0s for zero elmt✅
    3. Spiral matrix✅
    1. Leaders in an array✅
    ----------------------------------------------------------------------------------------------------------

    1. Two sum problem-

    return index of 2 elements in array which adds up to the target sum

    Brute-   time: O(N^2),   space:O(1)

    linear search with two loops

    -------------------------------------------------------
    Better:    time: O(NlogN),     space: O(N)
    mapping with two pass ( 
    first build the map & next do a linear search and find remaining sum in map )

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

    mapping with single pass
    (first check if answer exists & if not then insert the pair in map)
    Also, we prefer unordered map to reduce time complexity.

    ----------------------------------------------------------------------------------------------------------------------------
    2. Sort an array of 0s, 1s, 2s:
    Brute- time: O(NlogN) 

    sort the array
    -----------------
    Better- time: O(2n)

    count no. of 0s,1s & 2s and then overwrite using loops

    -----------------------------------------------------------
    Optimal- time: O(n) 
    DNF Algorithm
    (dutch national flag)
     3 pointer 


    we will iterate the array using middle pointer and see every time the element at v[mid]

    ---------------------------------------------------------------------------------------------------------------
                           3. Majority elmt [ >floor(n/2) times in array]

    Brute-       time: O(n^2)    space: O(1)                       
                                        
    we will use 2 loops and for each element count occurrences of it throughout the array and in this way we get our majority element

    also, we can sort the array and then use pointers to count frequency of each distinct element.
    -----------------------------------
    Better-      time: O(n)      space: O(n)

    we will use an unordered map and do mapping of each distinct elements and its count and then we iterate in the map to find majority element
    ----------------------------------------------------------
    Optimal-    time: O(n)     space: O(1)

    Moore Voting Algorithm
    Maintain a candidate
    Maintain a count
    When you see the same element: count++
    When you see a different element: count--
    When count becomes 0 → pick a new candidate.
    In the end, whatever remains must be the majority (if it exists)
    ------------
    Any majority element can't be fully cancelled out by pairing it with all other elements. So after all possible cancellations, the majority element must be the lone survivor.

    ---------------------------------------------------------------------------------------------------------------------------
                                     4. Maximum subarray sum:
    Better-   time: O(n^2)

    using two loops
    ------------------------------------------------------------
    Optimal- time: O(n)
    Kadane's algorithm

    Keep adding until it becomes harmful; then throw it away

    --------------------------------------------------------------------------------------------------------------Print subarray having maximum sum-

    ---------------------------------------------------------------------------------------------------------------
    5. Buy And Sell Stocks-1

    sell on i-th day and buy on minimum of 0 to (i-1)th day...
    so we need to store at every index the value which was minimum from start to index before this current index
    -----------------
    version-1: we can have 2 pass solution where first we build a helper array storing at each index the minimum element before that index

    version-2: we can solve it in single pass, where instead of a helper array we can just use a mini variable to store minimum buying price till current index.

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

    6. Rearrange array elements by sign
    (Alternating +ve and -ve)
    no. of (+) = no. of (-)

    we are required to build a new array & not the in place stuff in this question
    ---------------
    Brute:       time: O(2n)    space- O(n)

    use 2 arrays to store +ves and -ves and then update original array
    ----------------
    Optimal:   time:  O(n)      space- O(n)
    we put positive elements at even indices in the new array &
    we put negative elements at odd indices in the new array.
    ---------------------------------------------------------------------------------------------------------------------------

    7. Rearrange array elements by sign
    no. of (+) != no. of (-)

    Optimal
    :  
    time- O(2n)     space-O(n)
    pehle equal no. of positives and negatives alternatively bhardo aur fir,
    bache hue elements daaldo ...
    -----------------------------------------------------------------------------------------------------------------------------
    8. Find Next lexicographical Permutation of array:⭐

    Brute-              O(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-          NON INTUITIVE  (not for interview)
    implement the function ourselves:

    we will consider digits such that all digits to the right of this current digit are greater than the current digit. 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/4/3 ke right mein koi digit inse bade nhi hain. 
    -------------------------
    1. toh right se left tak breakpoint dhundo: a[i] < a[i+1]
    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...

    -----------------------------------------------------------------------------------------------------------------------------
    9. Leaders in an Array:
    leaders mean element is greater than all elements to its right

    Brute-        time: O(n^2)
    linear search for each element, ki uske aage ke saare chote hain usse ya nhi
    -----------------
    Optimal
    -    time: O(n)
    piche se loop chalado max ka var banake dekhte raho 

    -----------------------------------------------------------------------------------------------------------------------------
    10. Longest Consecutive Sequence-

    return length of longest consecutive elmts sequence which can be formed out of given unsorted array
    -------------------------
    Brute-       time: O(N^3)
    linear search for x+1 for every x and then inc count and update maxi variable
    --------------
    Better-       time: O(NlogN)    space: O(1)
    sort the array & then count max consecutive possible elements.
    Also handle edge cases like what if there are duplicate elements.

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

    insert all elements in a set
    and work only on elements which can be starting elements, i.e, a[i]-1 do not exist for them
    For such starting elements, count all a[i]+1, a[i]+2, etc. and then update maxi.
      
    -------------------------------------------------------------------------------------------------------------------------
    2d Matrix:
    It is a vector of vectors 
    It is dynamically resizable in both dimensions. e.g.,

    vector< vector<int>> mat(r, vector<int>(c, el));
    no.(rows) = mat.size();
    no.(cols) = mat[0].size();
      
    vector<vector<int>> mat = { {1, 2, 3},{4, 5, 6} };      2 rows
    ----------------------------------------------------------------------------------------------------------------------------
    11. Set matrix 0's:
    if an elmt=0 then set full row & col to 0s
    --------------------------
    Brute-       time: O(n^3)    space: O(1)

    for each 0 element in matrix, set its corresponding (non zero) row & col elements to -1.
    Now in entire matrix replace all -1 with 0s 

    ---------------------------------------------------
    Better-    time: O(n^2)    space: O(n+m)

    we will use 2 helper arrays to store indices of row or col which for a 0 element

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

    0th 
    row can store which columns should be 0
    0th column can store which rows should be 0
    if 0th row or 0th col itself needs to be 0, then we use flags.




    ---------------------------------------------------------------------------------------------------------------------------
    12. Rotate Matrix by 90° CW in-place:

    Brute-    time: 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-   time: O(n^2)       space: O(1)
    transpose krke har row ko reverse krdo

    ---------------------------------------------------------------------------------------------------------------
    13. Spiral Matrix:
    given a matrix print it in spiral order in a vector
    ---------------------
    Optimal:  
    time: O(n^2)   space: O(n^2)

    use 4 variables top, bottom, left, right 
    traverse the matrix from (L-->R), (T-->B),  (R-->L), (B-->T)
    Just add boundary safety checks before each traversal

    ---------------------------------------------------------------------------------------------------------------
    14. Count no. of subarrays with given sum:

    Brute- time: O(n^2)
    2 loops
    --------------
    Optimal- time: O(n) ⭐

    Using, prefix sum
     + map

    At each index, if subarray till this index has a sum x then we see how many subarrays exist before this index which have sum x-k

    At each index, we only care about sums occurring before this index.

    we set mpp[0] =1 to cover the case of k as the 0th elmt of the array ⭐
    -----------------------------------------------------------------------------------

    Comments

    Popular posts from this blog

    30.) DP on subsequences

    36. Graphs-2 (grid/traversal problems)

    19. Strings (LB)