0% found this document useful (0 votes)
19 views44 pages

Arrays

The document discusses various data structures and algorithms, particularly focusing on arrays, their advantages and disadvantages, and several algorithms for searching and manipulating arrays. It includes pseudo code and explanations for operations such as binary search, finding the largest number, reversing an array, and calculating trapped water in a histogram. Additionally, it covers topics like counting duplicates, finding missing numbers, and calculating maximum subarray sums.

Uploaded by

Dikshit Singla
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)
19 views44 pages

Arrays

The document discusses various data structures and algorithms, particularly focusing on arrays, their advantages and disadvantages, and several algorithms for searching and manipulating arrays. It includes pseudo code and explanations for operations such as binary search, finding the largest number, reversing an array, and calculating trapped water in a histogram. Additionally, it covers topics like counting duplicates, finding missing numbers, and calculating maximum subarray sums.

Uploaded by

Dikshit Singla
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/ 44

Day-d: Nouern

2L0003I1)S

Auoys of the Same data Type


slructore at shove elemens
,1 is a data
frovchoot in an Unbroken Seqyente) memory
in Conliguous (Connected
localion manipulate a olleclien
efficienHy
» provide a way to Organige and
of Reloted data.

Syalax: new int];

2. intC] arr =
3. int arrC ] 2, 5, 4,5,64

Dishdvantaqeir
Advantaqe 'itubo fiked Site
¿lemens Con be Accened directly'
USing aeir index.
it Con shore only Single dataype.
2. it Allocate Conliquus nerorg, Making
memory - eficenf"
taem mengrq
3- inserling And deleling eleed may
3. 8irgle and Skoightfotoand to dedlave Tequire shifing other elemenk, :
and Use.

4 il is good for Sorlng and Searchirq. 4. linied{lezibiily -lihe bound,


Checking impacling performante.
linear Seoreh.-Fiing tHhe
-the index ofHae elemen
laqem
2\000 31

inf n Senex Int (); Tere Complariy O)


int a() new in (n:
for (int i=o, ien;i4)

ari] St-nex\intt),
it (ai]--key)

Sop (kau is al hdex"i);


else

SopC'no tound')
2. Lagest Nober:- find the largest number in a giren Anay

i lage - Integer. MIN-VALUE -inteqer. MIN- VALwE


torCint i-o, isn; 4+) te- inteqger- MAX- VALDE
it carge aia)
Jarge - ati3;

else
3 Binay Search;
vsed for findng te element's Posiliorn in a Borted Array-
ilis
Nauer
2l0003|S
midd (short +end)fa ende-l
starlo

id-Ky
Mindekay
teadable.
Psevdo Code'- Simplified And humon
SBart o ,end =n-l
uhile (Stat &end)
Find id
’ Conpane mid &
eKoay
Code': Tine Complenl:
int storl =0 ,end enlengta-;
iteraion h
uhile ( Starte end)
.itevation h . !
mid (Start t end)/2:
ikeraton
if (hemid -- key) 4.iteraliornl8 -
retorn mid;

else it (ntmisdj zkey) kelog


Statt nid+|
Time Compleiky ogo
else
end =mid -
NNayeem
4. Reverse an L\00031|S
Ary Make a wap
Take first index And lastidex inder.
decreoe ue lat
Now in treae te firat inoer And
Code':
int fist o, last nerq
uhile (fFirgh zlost) Time Conpleniky- 06)
int (femp : n(lastd
(last] Suaping
n(firs4] temp,

last

’ for
prining the otput
Yeverse c) in Main fonclion
for Cint i-o; iLn-lengt; iH)
Syatem oot"pint (ni4 ");

S- Poirs in an 246|8 10
2’ (4) (2:6) (,8) (10) 4 Total pairs
4 (4,6) (4,8) (410)3
6 (68) (G0)

y Uing Noled loop Time Complerig '- Oln)


Code'- int Ap-o;
for Cint i-o, jen:lengt, i4)
int Corent nti;
tor Cintj it1, jznlengki)
,y Sop(+ Curent +"",4n+')):
tptt, ’ Total Noof pairs
6 Biot Sbanays AContinuous part of AYay

Nayeem
2,4,6 2,4,6, 8 2,4, 6, &,10 >s 21000 %11S
2,4

4,6,8 u,s,&404 ((ktort 2 end sn6,8,10


2Mi6,8
6 ’ 6& 6,8,10 3 k 2,4 2/4,6
Total: Is

logic:
- Findue start for (int ieo lon)
end for ( int j-it 4on)
, Find tue
Find Stort and end For (sfart to end)
3-
Code' in Total subarrayse 0)start 2
æjend 46,8,10
For Cint i-0; izn-lengty i44)
int starti;
for (int j*i: jenlengte it)
int end =j;
kzend k)
for ( int k- Stort,
Siop (on()

Sopht;
sop (4Total Sub anvay);
Add Sorge Conditions:
Riot Surm of the Cunrent subanoy.
2. Update minsum and maxSum.

3 Priot Total Subarays


Code' Nateen
Poblie stalie void Subamay (inl nt) 210003|1S

int tdal Sumbarays 0;


int minsum Inteqer . MAX-VALUE,
Int maxSUm Tnteger MIN - VALO6

lov( int i=o;, inlergh, i)


int stat i;
for (int j-i; jenlength itt)
int end-);
int (umentSum O; ’ Corvent Som
For (int k- Stort; keend; k+)
&opln (niu+" ");
(orventSum Korent Sum t ne;

nin Sum = Mat. min ninsum, Coment Sum)


max um Mata max (maxsym, (urrentsum)
Bopln ("ym" + (uvestson);
total Sulb aays tt;

Sojpln ("Tokal Subarayse 4 lotal Subaay)


`io plh ("Minimom Burs:"+ minsun)
Soph (^ Maximum Son" 4 maxsun
Input: 2, 4, 6,&, 103
oukpu 6
2
`um: 2 Sum:6 Syme l0
Somy
6
4
Sum:6 6 SUml
Sumi50 Som:10
6
6
Som:2
Total SubaMays - IS
2 Sum:18 Som:14 Minimum Sum- 2
Maximum Sum 30

Sum: 20 Sum:28
Max Subarray Sum (BRUTE foRc)
21000 b1|15

()1 Apptoseli'r
Mox 3ubaras'
(\2) ’ We oant To Take Vaniable
Value and "Corent Sum
(0-2,6) >s qve, tue Maximurn
uhich
of subarYay
(,-2,6,-)4 qive, te (orrent Sum wita Coireat
Marsobavray
’ taen we vpdak tue
Surm
Code:
int Current Sum O,
oukput
Inteqev.-MIN-VALlwE,
int max Sum: (-2) -
for (int i o, iLan:lengt i+) (,-26)> s
For (intji; jLr-leg;jt)
Cuventsom =0; (,-,6,-,)’7
for (int kei; Kuj; k4)

Cowent Sum -(urentsum + an(kJ;


G,6,-,)’6
if (maxSum < Corentsum)
maksum = (orrenfSum,

S"opln (Maxsum)
(6,3)>8

G,s) 2
Tine Compleriy
3bop: go
lon-Oo) Mox Sum ’8
uy Refir Anay Tme Conpliy On) Naeery

3
{or (stal ke end)
de
in he place of loo Add the Preßik formula To
-2+6161)

the Tme Cormpleicily


Code:
inf maxSum =Jnteqer.MIN-VALDE;
t new int (n-length:
Prefix fo] nfol;
l Caleulaling Pregix Aray
for Cint iel, iz Prefix lengt; itt)
Prefx tij Pre<ir Ci-]+ ntil;
for (intCi-o, izn-length; i4)
int stort - i;
for (int jei jentengtt)
int end =j,
Cynerk stort eo Prefix (end]: Prefix(end] - Prefix(stort-;
it (maxsurrn 2 Conent)
nax Sum Corrent;

Sopn('ira
max Sum+ maxSum);
) kADANC's
+Ve
+Ve
4Veceig) t -Ve(tran)’
(Bg)Ye
4VeCorau)4 -Ve
4-1

Corrent SumOo43|1|2 |4 2\600115


Maximum Sum' olo4|4|49:
~alyes Mohe if 2ero betause 3en
hadane's Telling -tat tue Iime we qel
’ than- Value
is qreaker
Code'
in Max Sum
Integer. MIAN. VALUE;
int CorrentSum e 0;

foy (int i-o, icnlengtu i44)


Covrent Sum t ni1;
if (CurrertSum< 0)
(orrent Som-O)

(CorentSorn, Moz Sum)


Mar Sum Mata .max

Sopln ("Mox Sum


ekorn - or "SmallatNegaive
Negalive
(ondilien if all number are
Max Som Integer. MIN-VALVE;
int
int (orYent Som e 0,
MAIN-VALUE;
int SmallelNeg Dneger-
for ( in! ie 0; iz n-lengt, i4)

Matumax ( GurreakSum , (oventSum +num)


(urent Sun
Max Sumn Matt max ( Max omy (orentsum);
Smallest Neg)
if(num L0 44 nåm>
Srmallet Neg numy
if,(MoxJum co)
So"pln (SmaleBNleg)
eliey&o-pln(MorJom)
tAovien,

(ode

7-21474a14 7
-21414794:0
in Polk ntij- byuphce;

buyie ni,
lrln mopoi

Rice,,s, 3,64} (4e1) (21)

(44614 ) M (o,-);

e)
5-7

M(o4)

() (1e6)
N(O1)
q Taging Roinwatev 1aueen
210003H1
Given n on. negdive inkeqprs tepveenling an erlevion Map there the cid te
of eah bar is 1, Conpute houw fmuth water it con trap after vain1g
oe want b know tae H much wdker is slored in blw tue kars
i
we have a Sinple fermch

water evel Maletf - Mon Pight kar


S
’ (w-x)* widte 2

(waterlevel - barlevel( heigh)* uidte


height 4,2,0, 6,3, 2s
I-bar ’ (0-4)* |4X O
1- bar ’ (4-1)*1e 2 O+244 40+2+ 3 +O =|
3-bar (4-o) tle 4
G. bar (0-6) l:-6X0 Irappeduater

(- bar ’ (5-2)* |:3


- bar
sorted in tue bars
The chante, tuat tae water will not
Q Single bar 0
2) 2bas ’

logic
r waterlevel -’ (Maxlet Moxkgh)
Tapped water ’ (onkertevel - hight)
To Find Molaiglt
’Use Aray
Left max boundary :- M4L]
max
Nlaueen
Code' 2\00031|1S
Roblic salie inint apedBinaler (w bighit) Tine Compleal Oun
inl n heigh length
lCaleulale legl may bouhdary voy

fi-1)y
let mar fid . Matl max ((heghtfi1, etmag
Il Caleulale Righl max boUndany -Aay
inl Right max(3: nw int (eighntongil
Rig max(h--height fn-1
for( int ixh-2; i>0; i--)
ra,(i41)2
RighB mox ti - Matlmax (heighicii, Right
l loop int Trapedwater -0;
for (int i=o, ien;i4)
int waterlevel Matlmin (legtmaxti , Righimar ti)
ragpedaler t= uatolevel -heightrid,
, Tekn Tappedualev;
Paclical 6Queslions
Nauee
find Hue duplicae values. if ere pint "roe 2\000311S

Code usinq Hashsek


Code' e>t):
Setnew Hahseà
lo (int i0, ienlergth t,ie) Hashset zinteger>
i-o,ienlengte,i)
for Cint
ForC j- it, je ttrgte;j)
if (sel ton fains (n eo)
it (atil a(a1) velurn frue,

Seladd (nc
So pln ('False ); ,relorn fale,

2 Count No ot 2evos
Code'
Poblie Stakie void Count (ink nc)
int (oont0)
i)
for Cinl I-o; ie nlengtay

(ount 44}
Sop ("oun!")
eteq
Sop)

3 Missing Nombevs ,4, , 3, 1,8]


Poblie stalie int Mizing (intC Jn)
n
iet e itom = n.length +
int expectelsum om k(un+) 2:
int Ackalsum -0;
for Cnt iso; izolength;iu)
Aclwal Sun t umg Ci1)

veluro expeckdSum - Aclualsur


4 find index in tue Aray of elensent which hib the Target it t doa

Tavaet prinl Nauetrm


The Algoitm be in O( lign) unline Conpli
Algorit' andend
inilialite too pointers "lel" And 'Righl, ko the begining
Respecivey
Oje a ahile loop for Pevfovm Binary Searth D
Caleulate tue middle
iddle index 'mid':
itis ,rekurn nid'as ke resut
S check if "n[aid "Tarqet".
Determine whieh halft of tuetothe
is eqval Array is Sovted: left or right
ihe leit half is Soted, check arget' is wtlin ae igt hal and
ifthe
"let and Rikl' Accordingy
7ifthe righB haf is Sorted, chech itue Targel" is wtin -tue vight half and
"le{" and "Righl" Accor dingy
-taat the Tao
Repeat skeps 3,t nll"'let is greater -han 'Righl,indicaling
8
is nt inthe Away
4. Relun '-1' is not foond intae Aray
indicate hat tue Targe"
Code'
Poblic Stalie int seaveh (int tJn, int Tarqet)
int left o,
int right =n: lergti;
while Cleftenigh)
int mid =ett +(ight -\et)
it(n fmid] =- Target)
rekorn mid;
Ilcheck which halt is Sorted: ett or Right
i
left half is Sorted
it (ntlet)s Target && Taget ennidi)
Li|Target is in the lett halt
, tight emnid-;
else, IlTarget is in te ight half
lett e mid41)

tie IRight half is torted


L uTarget is in tue right hat
let mid4;
’3
4+(l bright-tef)l, left4 mid
4eI eligh) (let while
mìd
legt
Iet-o RUN: DRY
2\000311IS mi-d ight
Nayeen
ball leyt is
the inTaget else
S You ave prites(i)is the priee of agen
qivern an Avoy Rie, ahne

hn e Maximumm Rofil youCan Achieve frorm


tis Transaken ityou
Cannl Achiere Any profil, ekrno Naueerr
2\00031115
Algpviti
)"tioite Buy' wi Aie bdy(0 and Profit wih O
aloop unl Vun al the Aica-lengt
By is len en Pricerij then
\ Tale Mox blw
s else Tolhe (Piceefij - Buy, Poi
( Ren tue Buy
ices
npul: Pi c¡¶: (4, \5,3, 64]
outpuk: S
Proflt e 6-1-s.
On day2 (Pice -i) and sell on doy s(iceo6) ,
>BuyDte kaf buying on day ) and Selfina on dayd is no Aloued beaue you mol
by Buy before you set
Code'
Public Salie void moxprofit (int ( 1Pica)
Prieatoj:
int Pofit -;
for (int iey i fricostength,it)
it (buy piteti)
Krofit= Mathmae (Pitetg- boy, hoftÝ);
ese
by- Pneyrs
Sop (PioflS
Riaht Rotate' Right o left Nayeen
left 2l00031|IS
Code' for N S, Key
Int kay SCnext+nlo; inpul: [, 2,3,4,t)

or(int i-o; izn,i)


Foytet, kye 2
arCi]- S(nextTnt()y inpo (,3 5,4]
ootpot- (s,4,,3)
tor (in j=o, i
LO;i41)
Srop(ar [aew index);

8 Right Rotate:
Nayeem
21000311IS
42 Tiapping Roin waler:-(hard)
height (o,,0,2,!,0,,3,2,,2,1)
Joguti-
vepeenled
Explaraion- The above elevakon mop is 2,].
2,,
by Aray (o,, 9,1) ,0,,3,vain water
unib of
in tis Cac, 6
are being trapped
Algo: eqval to 2, Yekoning9 0if rue a
lengt is len than or
PHChecka ithe inpot Aray
Nopping water Yecuives at leot s bars and vight maximom
and'righkMax', are Cveated to sfore the left
oo Aray, leftmax
for each
heighl bor index
tae keft marimum heighks by {raversing tue'height Avay From left
3 The Ago Calcolates
to righl
4 ximum heighh by kroversig tue 'heighl' Array
it Calcolates the ight maximum from
Simlay
SA variable 'rappedwokev is iniiali2ed ko 0 stove the kotal trapped waker
( The Algokerates trough tue 'heighf Aray Calalaing -te Traped water at each index
baed on te Mirieu of legt and vight maximun heights minus tue orent high
7. The Rewlt is skored in the 'Eroapped waler variable
Time Congieay
Spote Corgleiy: Oln
Code 2

int n- height engtlu 210003I||S

rekono |/ Cannet trap twater oitu ley itan 3 bars

int ( le{max
int Jrighmor
I| Calculale legt moxinm heights for each index
leftror (o] height(o3;
letmox (i1 Matt-max (legtmax ti-), height Ci1);

vight maximum
Yighlmax n-4-height (n-:
for( int in-2; i20, i-
ightmax i3 -Malumax (rightMax ti+1, height ti);
I Cglculat lrapped water at each index.
ink ragpedwater eo,
for int ie o i4n, it+t)L Mar

Lrappedwaler - frappedwaler +Mata min (leftnox ti3, Yightki) - height Cig,


telkwn happedwalery
’water level ’ (Max left, Mar Righ)
Traped wakr ’ (uatelevel -height)

left Mox i-= l-(e0 ,heo ’1>0


for 2Pol tue ma is I

Rght Mor

Min -o):
I2, Best Time to Buy and sell stock (tany)
Noyen
LI00031I
inie goor hoft by choing a Sogle day bo bay One stock and
Chocing a djerent day hthe fohoe to sel that skock
Telorn the moximom profi gou can Achieve from his fon saclion it you (annot
Achieve Ary Profit, tekon
Yelovn o''o!.
Inpt- Picos (3
oulpul s
Eplanaken: Buy on daye (ite ) and sellon day s(Pie:4) . Proit:1:5
Code- 06)
int buy - Pritesbk,
int moxprofit -c)
for (int i-o;
izpices.lergtii)
tCbye pite,tu)
in profi Pieoig -boy buj
max pirofi Metumax (ena pofihr profi);
else

elon moxprefib

{5
Prfi|-4
12 Best Time to Buy and sell skock i Noaueen
210003111S

day you may decide ko by andlor sell the stock. You Can onky hold at
Un each
at any Time. Hootver, you ton boy ten imm dhatey
nost one Shore of tue stock
Sell on the Same doy
Find and relrn tue maximym profit yov Con Achieve.
Jnpul- Ric - (3,5, 3,6)
and sell on days (Pice-s),Profit s:4
xplanalion :- Bug on day2 (Pice-i)
-6), Profite 633
on day s (Price
Ihen buy on day 4 (Price=3) and Sell
Total Profit is 443-t
L4,,5, S,{, 4]
Code:-0(6)
I>X
int maxproftit =0,
S ) s-94
for (int i- , iz prieslengtu i4) 1 375
6>3 6-3 ’3
t(Price, cij- Price,ti-)

moxprofit maxprofit +(Riestia - Rioyi-);

4+397
rekurn moxProiti
S3 Maximum Subaray (Medium) Nayoem
21000311IS
Given an ineqer Avay (mun), jind tue Sobaroy wit te larqut Som, and Te

pol nums (-2,,,4, -", 2, -S,4]


0olpol: 6
txçlanalion. he Scbaway (4,1,4,] hay he largot

ter4-) (2, )
’ (1) (2,1) (2, ,-3) (2,,-s,4) (-2,l, -3,4,-)
C2;\,-3,9,-, ,,5) (2,,-3,4-\,44')
-2

-4

Max Som = - (uweot Sum -

’ ,1,-3,)=42-444-0

’ (2,4,-3, 4,-1,) =l
’ ¢2,|, -3,4,-1, 2,) e4
|2, 1, 3, 4, ,9, )

(owent sum
(uwentsum - t

Currenl Sum -44


(ueot Sum o 4 |
(ured Sum -|49-| 2-1441

(uweal Sum I4l2


4-S -3
Cuwenl SUm
(uneat Sum -944|
ieralon &ievalor 216002,115
6ilevalion

-24 -Se-3
344|

Brote toCe 1- O(o)

int max Sum Integer. MIN-VALDE;


for (ink i-o; iz numslengt;it4)
for (int ji; je nomsleng-ta jt)

for (int Kei; ke) kA4)


Corentsom t noms («J;

{(Corentsom >moraum)
naxsum e (orrenbum;

Sop (mox Sum)


Sum in a

4Ve 4 +Ve

tve (BBi) 4 -Ve(smal) 4Ve


21600 311S
4Ve (Smal) 4 -Ve (Big)

(-1, ,5,4, -, 1,, -5, 4)

maxu L
Manhm-l
-320

’44
Maxlayr Marway
’3+2
4+!
maxwI Moxlaye -5 maxsumy

MaKo
maxa4
-SI6
Optimi2ed:-g
int Cwwent Sum- 0,

for(iot ico; iLums lengtu,itt)

it (rentsaum co)

Current Som e0)

max Sume Moemax(Curenbwum ,moxsum)

rewrn nan sumy


I| Container with mast water (Medu)
Find too lines that ogether wih tue x-ais form a Conkaleer, Such that the Contairer
Sontoins the most water. Noyeem
21000311IS
Relurn the maximum Amoun of waler a Cenointr Can slove
Max Avea

min (8,7) 7 -4g


(6,3) A:6t7 42

lelalle

Approach' 2pinter tight-8


max Area:Xo 2 3 4 6 8

min (left,ighd) *diakne


let let
right & i(lete tigt)t
34-18

higt-5
Code- O)
n ans -0 Noyeern
210003|||S
int let 0)
int tighnt heighk. lengta-t
while (legye igh)
int lengti Matt min (heighlt UeJ, higs GighN))
ins breath vighk -legt
int Areac: lengta * bueayy
ns Ma max,(ons, Area))

legtty.
else

Yight -
Yeluro ans;
(84 Rotate Aay (Medum) Nayee
21000 3I|15

Given an integer Amay (rom), otate the Aroy lo tae tight by 'k', skeps, here
'knon- negaive
k
Inpti- nums C4,2,s4s6,1),
Oulput- [s.4,1,,1,54]
Explonal'on:
totake steps to he light [4,2, s4, 5,6]
(13,9,s,43]
totale 2seps ko the Hight Is,6,4,,34)
totake seps o the vighl-
3

3 4
S 6 Rotate Rigtt by kshep
+ Revevse Aray
6 Spae Comçleiy Co)x0)
I-Reverse whale Aray
ke31.6=2
1 Reverne k elemert
element
2 1 3' Reverse n-

k- ky. site

’ tais Proble is done Recorsion f6 4S 219 2. 0, (h-1)


3-Klo-)

chohan approath!
TC! 0cny n -k K
Tenp aray L SC. 0cn
for( int in-k ien,)t+)
Tenpcinda4]: original avvaci)
original avy
lor cint izo, icn-kyitt)
Temp Cindex *+J= originaavrayci
Code 12

Foblie stalic in otate (int)nums,


n int ) L1000311S

K - K7.num lengta,

levevse (noms, o, n-);


Yevevse (nums, 0, k-1);
revevse Cnums, k,n-);
reton noms;

Yoblic stakc void tevevte ( int (3 hums, int stort, int end)

while (stort e end)


int tenp noms (slort );
Ngms (start] nums (end];
ums [endj \emp
Stars ++)
end --
In the Cose of it(k> nymslen)
| Revevse (o,n-) kekl.
2 Reverte (o,3)
3 Revevte (h, na)
(w2iwl -arow oot ot bound
Main :
Peblie stalic void main (sling C1 avg:)
int noms ] ,s3:
int k4,
SopCAay tosing(ohate (rumyk));
I: Tuoo Som (t:iny) not
one solokion ond you ay
You nay Astome tat each inpot wculd have exacty
Noyerm
Use tae Some element wice. 2\0003115
You Can rebro he answer in eode order

Inpul'- nums - (,4,,15], Tarqet -1


Outpul:- Co, 1] numstrj -9, we relurn (o, ].
Nomso] 4
xplanaor- BecaySe

Code: Noms, int fargel)


Poblic int) two Som Cintc
neDymslengt
int Sum - o) int Tioe Comaleily
for (iot i0, ien;i+)

Sum target - DumstiJ;


for (int jei+v jenjt4)
<j:)

vefurn new intci,i

tekoro new int (J4-,-iy


26 Remove Duplicates trom Sorted Aray (Eony)
gouneed
Consider e number of unique elemenks of "nons' to be 'k, to get hcepted
to co the follcoing ingp -
tirct elemery of hums Contoin tue Onique
e Aay noms" Such tuat tue
2e ot "oms!
elemenb f "noms"are not important OÀ well aA ue Si

’ Rekoro "k". Nayeem


L100031|S
Exomple numS = [l,,2]
Inpuk'
oukput- 2 rekorn Ke2, with the first two elements of noms bing
xplanation'- Your unchon Shoold
1i ond 2 re,peclively
n mater wba yoy leave baond the vetuned K(hene taey
I doe,
Unders cores)

Code'
Poblie int remove Dopli cales (int C]ouns)
i{C noms-lengt =-o)!
rekovn 0
int i-o;
for (intj- (y jenomsleng;jH)

teturn i+
13 3Sumn (Medium)
(numso,fens(, nuns(«)
Given an eger Avay nynt, reon all the higlets (hum 6o,
and j!k, and noms(0+ noms(jJ+ numsJ0

tuot -tue Soloion set mus nol Conkain doplicale Tiple


Nolioe
Nayeer
Example
Lnpul: nvmg -,0, , i,-, -4]
2100031IS

Outpol: [-,-,2), (-1,0,1)]


planation

The distint Triplels are (-\,0, ) and -l, -, 2]. Triplek does not matter.
and te order of-the
Nolice that tue Order of the ootput evorsi
Sample Code wit
Agproac: Poblic void -tareeom (int
(Javy, int Targe
t- Sort Aray Avayg-sort(am):
2 Use thue tree pointer jj.k) forCint i-o;&icarenga; itt)
jeu) (oe1) iN jei+
Su itj +h ’ -lto+I
hhile (jek)
L
-l,0,!
it (Sum=a arget)
(1:
Jop(anti)+,"4avt) + "4anl):

eke if (Sum clmgel)

etse
K-
Geks tor qeeks Naueern
Choco late Dislibolion Roblem 2\000 3111S
N inheqers where eoch vabe tepresena tt No of chollaey in apackot toth
distribote
Parkel Can have a Vaiable Ao of chotolales Thore are Mshudenb,the task islo
chotelote Packeb such tot
* Each sludent ges One Pockel
chocolae, cnd tae
The ditferene between te No of cheolotes ntse Pachet otth moximun
Pachet wth minimUm chocolgkes aivea o the students is minimum

Example
npot:- an] -{1,3 2,4,4,12, 56y,m3
Outpol:- Miniom difevence is 2
Cxplanation:- we have Seea Seren Rackek of chocolaBes and we need to pick -taree Paches for s
Sudenk
and minimu acker
TOC pick 2 3 and 4, we aet he Minimom difference bekoeen Maximum

Approah And declare a Variable to store tue


minimm ditferente
Sotthe given Aroy let te variable be min.dtl
and iniai 2e it to INTMAX. sorke)
betueen -he last (Mar in tae of
Sobaray of sige mSoch that-tue ditfevence is minimom.
nde elemenb of-he Subaay
and fist (minimom in Coe of Sorted ) the sie
(h-m), auhere n isthe Si9e of-te qi ven Array and mis
Swe will Yon a kop tvom Oto
of te Seboray ond stoe it in
4 we will alculate ae maximunm differente witatae Sub array

dit ar [highed index] - ar [louol indkr)


s. whenever we get a dift kn than the nin- diñt, we will
pdahe the min dft ioita ditt
19

nin.diff - NL MAX
Soied Anay'
6 Alayeer
2\0008111S
g'’ 4
Step- I:
itn-!

- atij e min - ditt : Üpcate min.ditt


Here aci+m-]
Citm-]. ali)
min. diff a

4
sBep-:
I+3-!
’3

3-14 min dit (1).Do notain9


19 S6
3
SBep-3:
243- 2

norting
4-2> min - diff (2) ·Do
S6

Step-q 343-1

s-3> min. ditt() - Do otuing


12
4
Step-s
4+3-1

(-4 min- ditt() .Do notaing


Code
Poblic alic int find (int(1ory, int m)
Zi00031l|S

int n: o leng
int Ans J teger. MAX.VALUE,
vay. Sorl (on);
for( inl iro; 14 n-; i4)
int min afi3;
inl mox a[itm-];
int gop "max-nin,
it Cgap zans)
ans 9ap)

Youvn ans,
Poblic stalic void main
int(3 arr 13,3, 2, 4,9, 12, 54;
int me 3

Sep(Find (avr, m)
Iner view Bit 2

Repealing and Mising Numbtr Amay CMedon) Nayeern


2\0003|LIS
You are given a Tead ony Array of n inteqers from 1 to and B8 whieh is
Once except A which Appears oice
toch integer Appears exotly
Mising
Retovn A and &
should hove a linear Yonlime Complexiky Coold yeu inglenent i wieu*
Note: Yoor Algo
Uaing &tro meney?
pretede B-
’Notetat in your outpot Ashould
arre 4 3 6 2 U0-6

brote force: 0(n)


Repecling Mising
for (i=e I ’ )
Count =0)
for(j20 ’ n-)
it (orj3em arii)

it (ouny) tit repeaing nomber Repeaing i;


elte if Count o) Miking i
1-1)

breck);
Gode' Brue tovce
Int n alengte
21000311s
int tepeating:, Misingb
for (int i- ini4) Aprooch
int Coont -O;
Orrunente in the
».fov eoch inter, , oe willCount is
fer (int jojenj") given Airay vsing (ineor Seoeh.
3 we orll store ose oo
elemenh -hat have tue
{ (acj aio)
Ocowente of ) and 0
Ceuni 44)

iCeort ) lepealing
else if Crunt eo) miting Time Conpleaiy Ocw)
(repeatng ! missing ) Spae Compleaih 00)
break,

int co ons -epeaing, ising9


lekovo anS>

Mat'
OSing 4 2+ 3+4.. n. Dx(ot)

Qr: 4 3 6 2I]
*’ Repealing
So
(t-5)

Repee

( t ) -24

[>Bepealing
23

2l000311|5

Sep t:- So (N4 (Nt))/2 of all-e elemens in the given Aray


0 S- Sommation
Stepd- S- Sp X-Y
step2:- S2n- (N*(NH)"N4)) le Tire Compleiky- Oto
S-Sin Xg-Y
Spate Comçdeiy 00
X{Y- (5)-Szn)/(K-) 0

Approach fepeaing and Yto be mising ronber


Assome the epeaing Xto be S-Sp éqs0
and then Caleolate
values of S and Sn
| First, find out ae andtuen Calculate S- S2n:
S2n
Then, Find out tue valve, oft S and ty and X-Y. Nou,by
2 oll be "ke
having valbes of X
d and 2, we
3 After Povfovning Sheps Can easiky findtae vabes of Xandy
Substitufion of value, we
Code
long n- alengta;
long Sn- (nt
(h+))|2;
long Sine

forl int ieo; ien i4)


ai1
S Sy +(ong)arig (bng)
e X-Y;
long vale S- Sns l S-Sn
-Szn - X^2-y^2
long val Sa- Szn; / S,
vale : val/val; (Find
val)l: IEiod Xand Y; X ((XH)+(*-)|: and y. x- (*-)
log x (val +
long X- Val1, I| Here, X-Y val, and X+Y e valu;
int(J ant: {(ind)x,Cin)gy,
return ans,
leetco de
33 Seaveh in Rolaled Sonled Aray [Medum) Naueern
LLo00 31||5

Hior to be ing pased to your funelion, 'nons' is po sibly Yotated at an unknan pive
Index K(Ie Ks, munglengk Soch tatthe tesuling Aray is rons (u),um:(wil, , (0-1ndexe .
To ¿xnole Lo.,2,4, S, 6, 1] might be tolated af Pivot index 3 and becone [uSi6,4,0,2].
huns agler the posible totalion and on inleqev orget', vekorrn toe inser of
Given the Anay
'nom'.
targel { iFis in nums',oris not in
You most wvite An Algoitiy oit O(rgn) online omplei
Inpoti- UmS - (4,S,6, 7,&,91,!], lavget o

Irpot-nuns- (5,6,7,0, 2], Target,


Ootpuf- -i

Approach is ike binear Seaveh wita he Time Compelkiy


tue Basic
And Sorted we Can go toy a
So, tuat it is a Terms ke Search"
tom Ot to 0Cbgn).
Search ,So tuat we Can ninimi e the ine (ompleiy
Biroy
lel's Com Back to tue
Tongel Torgel s Noeor,
2100031l15
mid
Low high
So, that oe Compare 3-. Torgel t) X
le 3’ in -lis Cae he Righl pad is tliminated
-the Tagel in he lett pavt
Now,

S<3 in tis Cae -e legt pavt is limingled.

Jusf checking of -the One half was


Righn
nUms] 4 &912 4S 6
mid high
nSorted
’2== |X

’ l42
’ eliminate Ohe halt
let hond Side
In Cane of the larget 8
842 X y then kis never lie on the let holt
’ for the given Prbl we Cannot eheck the One half beCaute il
is not &ovted.

Tdernity the Soikd half ’ let Rignt


for checking in Rignt half we Ca 24l26’tae Tarel is co Rreen hen
eleininale te halt
then we want lo move -the high.
md} high
else anc Jre
mjd; high else
(mid)) avr tavqel <rged (ar(io] it
md)) qr tlou (on it
nid, vekrn argel
rge) ) (mid) sovded (or Illet it
(lwthigh)IL mid
high) (lowA while
highn-I O,locw-
21000311US high Mid
T1
6
Code'
Noyeem
21000311S
in low o, high
while (loaw shigh)
int mid (loco +high) (2;

H(ums (mid] -- Targel)


tekovn mid;
Il lett part is sorted
if (nums Isw) e nons (midy)

ke nums (midi)
f (omy(low] k e
Ilelerent exish
high mid-;
else
L lelemeot doe not exist
louy - mid +

ese it vight part is Sorked


if(ovr (mic) s ke4 keartengta (igh)
Lielement exib
louo =mid+;

high: mid-b
leetcade
Element inan Avray [ Medim] Nayeer
215. Ktu Largest 21000311
klarget
aqet element in
iivn an ntegen Aoyoms ond on integer 'k", rehoro te
the Anay not the 'uk
'k" element in tue Sorted order,
Note that i the is he larqest
distinct element
Can Solve

xomple ,5,6], k=4


(3,2,1, 5,6,41 ,ke) Inpul' noms [3,2,3/,2,4,
npot ums
Ovlput- s

fhoblem Explan glion}- So, we coant ko find tue k largot


Sorted ovdev
Sorting Aporo achi
6 4
3 2 S
K-2
3 2
Soting in (desning ode?)

2 S6
3
3
3 3
Sort 6
Code' Nayer 29

210003115
t noms, int k)
int find KttaLarqest (vector eint Order
end), greater zint7(i); I| de stending
Sot (numsbeginc),nomns
Yeturo Nums [k-j;

And tacre is a Anoter Oplini 2ed Aopvoachi the Top largest elenenhis there)
Heap > Max Heap (at
Min Heap

S
3 2

Max heap
log o
(logr)
’ adding in he morheap
Moz heap TC:- (nbg)
’ insevt all elemenb in
(k-i) ime, fron maxheap
’ we pop element
max heapr
’ The lop of

(spate Conpleciy
The Oplini |ed ieoeSC:-0(K)
Te:- nbgk
Klargo
grealett>Min htap
Max
3 S 6
L K2
fiyst k een 2\00031|)5
’in Minheap elemend
we will have k
Akoay in min heap elem onta
’ Min Heap (onlinules Top K-

|22 (Top of min heap)


S>2 (Top of min)
6>3 (Top)

Code'
Poblic int findka Larqet (intL J nums, int k)

PhioilyGveve L+ntegety min Heap


| itevate tough the Array and add elémeslb to the Min Heap
for (int nom: nums) 1
minHeap otfer(oun);
exceed k, emove the Smalles element
min Heap
Ii te site ot te
Sige()> k)?
f (min Heap.
minHeap-pollo;

tue Kta larged elemert


VThe Yemaining element in tae Min Heap is
Veturn minHeap- peek (,

You might also like