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

Array

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Array

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

1) max = a[ 0 ]

1) Largest element in an array 2) compare it with


Input: other ele of array
arr[] = {2,5,1,3,0}; 3) max < a [ i ]
Output: max = a [ i ]
5 // largest element in the array. return max
B.F ( basic mtd)
sort( a.begin(), a.end() ) ; => return a[ n-1 ]

T.C = O(N*log(N)) , S.C = O(n)

T. C => O(N), two linear traversals in arry


Find Second Smallest and Second Largest Element in an array S.C = > O(1)
B. F = > works if there are no duplicates Solution 2(Better Solution)
Better
Optimal
124577

Solution 1: (Brute Force)


[this approach only works if there are no duplicates]
1) sort => a[ 1 ] ( 2nd smaller ) , a[n-2] (2 large)

T. C

S.C

T.C = > O(n) single pass


Solution 3(Best Solution) S.C => O(1)

Check if an Array is Sorted


Brute Force Efficient (Single traversal)

T.C = > O(N^2)


S.C => O(1)
O(N) O(1)

Remove Duplicates in-place from Sorted Array Two pointers

Brute Force => hashset => stores


unique elements.

unique elements are 3, i.e[1,2,3]

return 3

T.C = O(N)
S.C = > O(1)

Left Rotate the Array by One


Brute force Approach

S-2 :->

Rotate array by K elements => either left or right.


S-1 => Using a temp array

k array element needs to be stored in temp


array

S-2 => Reversal Algorithm

Move all Zeros to the end of the array => and move non-negative integers to the front by maintaining their order.

Output: Using 2 pointers


Input: 1 ,2 ,3 ,4 ,1 ,0 ,0 ,0
1 ,0 ,2 ,3 ,0 ,4 ,0 ,1

S-1 => use extra array

Linear Search
S-2 = >Set

I./p o/p
n = 5,m = 5. {1,2,3,4,5}
arr1[] = {1,2,3,4,5}
arr2[] = {2,3,4,4,5}

s-1 => map

Find the missing number in an array

o/p
I/p 3
N = 5, array[] = {1,2,4,5}
T.C = O(m+n),
S-3 => Two Pointers S.C = O(m+n),

Hashing
Count Maximum Consecutive One's in the array => arr-> 0 & 1
Input: prices = {1, 1, 0, 1, 1, 1}
o/p => 3

S-1 => b.f => linear search & cnt occurance


Find the number that appears once, and the other numbers twice
i/p arr[] = {4,1,2,1,2}
o/p => 4 Hashing using the map ds

Optimal apr => xor


a^a = > 0
a^0 = > a

You might also like