0% found this document useful (0 votes)
3 views

array

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

array

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Q.1) find second largest in the array?

Brute-force: Find largest and by using this find second largest.


Optimal: Use largest and second largest concept in same loop

Q.2) Remove duplicate in-place for sorted array?


Brute-force: Use set data structure to store and then place it in same
array
Optimal: Two pointer approach check previous pointer with current
pointer
int i = 0;

for (int j = 1; j < n; j++) {

if (arr[i] != arr[j]) {

i++;

arr[i] = arr[j];

Q.3) Left rotate the array by d-place?


Brute-force: store element of array till ‘d’ in temp array and then store
d+1 element at index 0 to d and then store temp element in array.
Optimal: reverse(a,a+d);
reverse(a+d,a+n);
reverse(a,a+n);

always (d=d%n) [no of rotation must be less than size of array if rotate
the array equal to its size then we get same array]
Q.3.1) similar concept for right rotate also?
reverse(a,a+n-1-d);
reverse(a+n-d,a+n);
reverse(a,a+n);

Q.4) Move all ‘0’ to last?

Brute-force: Count non-zero and zero and put non-zero up-front and
then use zero
Optimal: first find the first 0 where it occur then Use two - pointer
Q.5) Union of two sorted array?
Brute-force: Use set two store both array and store in array to return
Optimal: Use two-pointer one at first array and second at next array
and take in union array which is smaller and move pointer and at last
the array which is remaining store in union , use unionArr.back()
(consider the case if unionArr.size()==0) for previous array element
comparison and run while loop till (i<n1 and j<n2) .

Q.6) Intersection of two sorted array?


Brute-force: Use two for-loop and visited array which tell wheter
element is previously used or not
Better: Use set and its size concept.
Optimal: Use two pointer one for each array and if array element are
equal put them in intersection array and move both pointer and if they
don’t match move the smallest element pointer

Q.7) Find the missing element in an array ?


Brute-force: Use two loop to check whether every element is present
between 1 to n.
Better: Use hash map i.e, an array of size n+1 to store all element the
one that contains 0 is missing element.
Optimal: Sum 1 to n and subtract every one from total sum remaining
will answer
More Optimal: Take xor1 in which store xor till 1 to n and take xor2 in
which store xor of array element we get answer
Xor solution is slightly better than sum because sum can exceeds
which we have to store in long so xor is better which value can not
more than n.

Q.8) Max consecutive ones ?


Take cnt=0 ans maxi=0 when 1 cnt++ update maxi and when 0 in array
make cnt=0, return maxi.

Q.9) find the no that appear once rest are twice ?


Brute force: Use hash map i.e, an array of size maxi to increase the
count of each element and one that appear once is our answer
Better: If array contains 109 element then we use map to store
Optimal: Use xor concept to find unique.

Q.10) Longest subarray with sum k ?


Brute force: We generate all sub array and find sum and check size,
Use 3 loop 1st (from 0 to n) , 2nd (from i to n ) 3rd (from i to j), we can
remove third loop because every time we add just one extra element
Better: we use map If sum till index i is x then if x-k exist previously in
map then we can say that subarray with sum k is here then we update
length if greater we keep index in map with sum. But this approach
fails if array contains 0 so put sum in map with index if previously sum
is not existing
Note: this is optimal solution if array contains - element

Optimal: Use 2 pointer approach if sum ==k find (j-i) and update length
if greater and sum exceeds k then trim from left i.e, subtract ith
element move i to i+1

Q.11) Two sum problem ?


Brute force: Use two loop to find whether sum is equal or not run first
loop from 0 to n and second loop from i+1 to n.
Better: We use hash map to store array element along with index and
check if x is there we check whether (target-x) exist in map or not
Optimal: Sort the array and use two pointer one from start and other
at end and check if less than target move start otherwise end--.do till
left is less than end.

Q.11) Sort an array of 0 ,1,and 2 ?


Brute force: Use any sorting algorithm.
Better: Count no. of 0,1 and 2 and put in array (Use only two variable
find 3rd by (n-first_two)
Optimal: [Dutch National Flag Algorithm]

0 Low-1 low mid-1 mid high high+1 n


[ 0000000] [111111] [unsorted] [222222]
Our array
When are between mid and high and our low is also at first index i.e 0
now we have 3 condition
1. If arr[mid]==0 we swap(arr[low],arr[mid]) low++,mid++
2. If arr[mid]==1 we do nothing otherthan mid++
3. If arr[mid]==2 we swap(arr[mid],arr[high]) high—

Q.12) Majority element we have integer find the array which has more
than n/2 appearance ?
Brute force: Use two loop to find the count of each element and one
which has count greater than n/2 is our answer
Better: We use hash map to store array element along with its count
the one which has count greater than n/2 is our answer
Optimal: Moore voting Algorithm
1.Apply moore voting algo
2. verify whether this element appears more than n/2 times or not
Take two variable cnt and majority_element when cnt is 0 change
majority element and when equal increase cnt otherwise decrease cnt

Q.13) Kadane,’s Algorithm , Maximum subarray sum ?


Brute force: Use 3 loop to generate all subarray with their sum and
find maximum one
Better: Optimize above code to 2 loop to get sum and find maxi.
Optimal: Use of Kadane’s algo
Use 2 variable maxi and sum if at any position sum is (negative) no
need to move it further make it 0 but before updating update maxi if it
satisfies the condition
If we have to print subarray
Take 3 extra variable start ,ansStart, ansEnd whenever our some is 0
initialize start with that i and when sum>maxi update ansStart and
ansEnd

Q.14) Rearrange element by sign one positive and one negative array
contains equal no of + and - element ?

Brute force: Use 2 array to store positive and negative element and
then put in + element at even index and – element at odd index.
Optimal: We create answer array and check if element is + put in even
available index and if – put it odd available index

Type 2 : If no of positive and negative are not equal then we can’t


apply optimal solution then our brute force is only the way to solve
the problem. Take two array and store + and – to store in ans.

Q.15) Find next permutation ?


Brute force: Use recursion to find all permutation use loop and
frequency array for generating permutation.
Better: Use stl next_permutation(A.begin(),A.end()).
Optimal: we use to write code for next_permutation. And we need to
find break point where A[i] < A[i+1] at that place we try to find which
is greater than A[i] but smallest on right and swap them. and place
rest of them of right in sorted order[or reverse it].

Q.16) Find leaders in array ?


Brute force: leaders is the element in which all element on its right are
smaller than this element So we run 2 loop and check if any element
has greater value on its right it is not leader.
Optimal: Run loop from back and check whether this element is
greater than maxi on its right if yes put it into leaders array.

Q.17 ) Find longest consecutive sequece means if I pick 1 then I check


if it contains 2,3,4,5,6 and so on ?
Brute force: Use two loop one for every element and
while(linear_Search(arr,x+1)==true) )x++ , cnt++ and write function for
linear search.
Better: Sort the array and take three variable lastSmall, curCount,
Longest.
Optimal: Store all element in the unordered_Set and then start check
every element previous if its previous exist then we don’t start from
that element E.g [102,4,100,1,101,3,2,1,1] if we start from 102 and
check does we have 101 yes we have means we can start from 101 so
leave for now and so on repeat this process for every element.

Set matrices to 0 i.e, if any row contains 0 mark that row


Q.18 )
element with 0 and if any colm contains 0 mark that colm with 0?
Brute force: Use two loop and check if arr[i]==0 markrow =0 and
markcol=0 and earlier we mark with -1 to avoid unwanted 0 after
finish we convert -1 to 0. T.C= O(n3)
Better: We take two array one for colm and other for row track then
when ever we got 0 in matrices we mark that row and colm in our array
and after that we again iterate in matrices and check if that row and
colm is marked if yes we convert 1 to 0.
Optimal: it is similar to better but instead of making different array for
row and column we use same matrices matrices first row for all col
and matrices first col for all row and we use one extra variable col0 for
collision point i.e,matrices[0][0]. And we solve for 1 to n and 1 to m
then convert first row of matrices and then first colm

Q.19 ) Rotate matrices by 90o or Rotate image by 90o?


Brute force: Make n*n matrices and put first row element in last colm
and second row in second last colm and so on. ans[j][n-i-1]=matric[i][j].
Optimal: Take transpose of matrices and reverse every row care on
transpose, for(i->0 to n-2) and for(j->i+1 to n-1) swap(mat[i][j],mat[j]
[i])
Reverse(mat[i].begin(),mat[i].end()).

Q.20 ) Print matrices in spiral order ?


Better: Right -> Down -> Left -> Up (Movement of our spiral)
Other solution while(true) take character and visited array and R,D,L,U
And do for all four condition.
Optimal:
// Initialize the pointers read for traversal.
int top = 0, left = 0, bottom = n - 1, right = m - 1;

// Loop until all elements are not traversed.


while (top <= bottom && left <= right)
// For moving left to right
for (int i = left; i <= right; i++)
ans.push_back(mat[top][i]);

top++;
// For moving top to bottom.
for (int i = top; i <= bottom; i++)
ans.push_back(mat[i][right]);

right--;
// For moving right to left.
if (top <= bottom) {
for (int i = right; i >= left; i--)
ans.push_back(mat[bottom][i]);

bottom--;
}
// For moving bottom to top.
if (left <= right) {
for (int i = bottom; i >= top; i--)
ans.push_back(mat[i][left]);
left++;}} return ans;}

Q.21 ) Count subarray sum equals to k ?


Brute force: Run 3 loop to generate all subarray sum and find count
which sum equals k.
Better: We can remove 3 loop and do this using two loop only
Optimal: cnt, prefixsum, map store [cnt,sum-k] put mp[0]=1;

Q.22 ) Pascal Triangle ?


Type 1: Given row and colm find that element then we use row-1Ccol-1
and find factorial to calculate value.
Res=res*(n-1)
Res=res/(i+1) 10/1 * 9/2 * 8/3 find factorial in this way
Type 2: Given row no. and find that row run loop from c=1->n and find
fnNcr(n-1,c) optimized approach is ans*(row-col)/col)

Type 3: Find pascal triangle given n we run for loop for every row and
compute value for every row like ans*(row-col)/col)

Q.22 ) Maximum product of subarray ?

Brute force: Run 3 loop to generate all product and find maximum
one.
{1st loop: 0->n, 2nd loop: i->n, 3rd loop: i->j }
Better: We can remove 3 loop and do this using two loop only
 for(int i=0;i<n;i++){
o pro=1;
 for(int j=i;j<n;j++){
 pro=pro*arr[j];
 ans=max(ans,pro);}
Optimal: Do product from front and back find maximum product and
before doing product check if front product is 0 make it 1 and also if
back product is 0 make it 1.
First update front product and back product in answer then in next
iteration check if product is 0 make it 1.

You might also like