question
stringlengths
58
4.29k
label
class label
3 classes
give integer array num length n want create array ans length 2n ansi numsi ansi n numsi 0 n 0indexedspecifically ans concatenation num arraysreturn array ans Example 1input num 121output 121121explanation the array an form follow an nums0nums1nums2nums0nums1nums2 an 121121example 2input num 1321output 13211321explanation the array an form follow ans nums0nums1nums2nums3nums0nums1nums2nums3 an 13211321 Constraintsn numslength1 n 10001 numsi 1000
0array
give string s return number unique palindrome length subsequence snote multiple way obtain subsequence count oncea palindrome string read forwards backwardsa subsequence stre new string generate original string character delete change relative order remain charactersFor example ace subsequence abcde Example 1input s aabcaoutput 3explanation the 3 palindromic subsequence length 3 aba subsequence aabca aaa subsequence aabca aca subsequence aabcaexample 2Input s adcoutput 0explanation there palindromic subsequence length 3 adcexample 3input s bbcbabaoutput 4explanation the 4 palindromic subsequence length 3 bbb subsequence bbcbaba bcb subsequence bbcbaba bab subsequence bbcbaba aba subsequence bbcbaba Constraints3 slength 105s consist lowercase english letter
2string
you give n BST binary search tree root node n separate bsts store array tree 0indexe each BST tree 3 node root value in operation canselect distinct index j value store leave treesi equal root value treesjReplace leaf node treesi treesjremove treesj treesreturn root result BST possible form valid BST perform n 1 operation null impossible create valid bsta BST binary search tree binary tree node satisfie follow propertyevery node node leave subtree value strictly nod valueEvery node nod right subtree value strictly great node valuea leaf node child Example 1input tree 2132554output 3251null4ExplanationIn operation pick i1 j0 merge trees0 trees1delete trees0 tree 325154in second operation pick i0 j1 merge trees1 trees0Delete trees1 tree 3251null4the result tree show valid BST return rootExample 2input tree 538326output ExplanationPick i0 j1 merge trees1 trees0Delete trees1 tree 53826the result tree show this valid operation perform result tree valid BST return nullExample 3input tree 543output Explanation it impossible perform operation Constraintsn treeslength1 n 5 104the number nod tree range 1 3each node input child grandchildrenNo root tree valueall tree input valid BSTs1 TreeNodeval 5 104
1graph
there malfunction keyboard letter key work all key keyboard work properlyGiven string text word separate single space lead trailing space string brokenletter distinct letter key break return number word text fully type keyboard Example 1input text hello world brokenletter adoutput 1explanation we type world d key brokenExample 2input text leet code brokenletter ltoutput 1explanation we type leet l t key brokenexample 3input text leet code brokenletter eOutput 0explanation we type word e key break Constraints1 textlength 1040 brokenletterslength 26text consist word separate single space lead trail spacesEach word consist lowercase english lettersbrokenletter consist distinct lowercase english letter
2string
you give strictly increase integer array rung represent height rung ladder you currently floor height 0 want reach rungyou give integer dist you climb high rung distance currently floor ring rung dist you able insert rung positive integer height ring therereturn minimum number rung add ladder order climb ring Example 1input rung 13510 dist 2output 2explanationyou currently reach rungadd rung height 7 8 climb ladder the ladder rung 1357810example 2input rung 36810 dist 3output 0explanationthis ladder climb add additional rungsexample 3input rung 3467 dist 2output 1explanationyou currently reach rung groundadd ring height 1 climb ladderThe ladder rung 13467 Constraints1 rungslength 1051 rungsi 1091 dist 109rungs strictly increase
0array
you give m x n integer matrix point 0indexed start 0 point want maximize number point matrixto gain point pick cell row picking cell coordinate r c add pointsrc scorehowever lose point pick cell far cell pick previous row for adjacent row r r 1 0 r m 1 picking cell coordinate r c1 r 1 c2 subtract absc1 c2 scorereturn maximum number point achieveabsx define asx x 0x x 0 example 1input point 123151311output 9explanationthe blue cell denote optimal cell pick coordinate 0 2 1 1 2 0you add 3 5 3 11 scorehowever subtract abs2 1 abs1 0 2 scoreyour final score 11 2 9example 2input point 152342output 11explanationthe blue cell denote optimal cell pick coordinate 0 1 1 1 2 0you add 5 3 4 12 scorehowever subtract abs1 1 abs1 0 1 scoreyour final score 12 1 11 Constraintsm pointslengthn pointsrlength1 m n 1051 m n 1050 pointsrc 105
0array
there root tree consist n node number 0 n 1 each node number denote unique genetic value ie genetic value node x x the genetic difference genetic value define bitwisexor value you give integer array parent parentsi parent node if node x root tree parentsx 1you give array query queriesi nodei vali for query find maximum genetic difference vali pi pi genetic value node path nodei root include nodei root more formally want maximize vali XOR piReturn array ans ansi answer ith query Example 1input parent 1011 query 023225output 237explanation the query process follow 02 the node maximum genetic difference 0 difference 2 xor 0 2 32 the node maximum genetic difference 1 difference 2 xor 1 3 25 the node maximum genetic difference 2 difference 5 xor 2 7example 2input parent 37120702 query 4611505output 6147explanation the query process follow 46 the node maximum genetic difference 0 difference 6 xor 0 6 115 the node maximum genetic difference 1 difference 15 XOR 1 14 05 the node maximum genetic difference 2 difference 5 XOR 2 7 constraints2 parentslength 1050 parentsi parentslength 1 node rootparentsroot 11 querieslength 3 1040 nodei parentslength 10 vali 2 105
0array
give string s return true s good string false otherwisea string s good character appear s number occurrence ie frequency Example 1input s abacbcoutput trueexplanation the character appear s b c all character occur 2 time sExample 2input s aaabboutput falseexplanation the character appear s ba occur 3 time b occur 2 time number time Constraints1 slength 1000 consists lowercase english letter
2string
there party n friend number 0 n 1 attend there infinite number chair party number 0 infinity when friend arrive party sit unoccupied chair smallest numberfor example chair 0 1 5 occupy friend come sit chair number 2When friend leave party chair unoccupied moment leave if friend arrive moment sit chairYou give 0indexed 2D integer array times timesi arrivali leavingi indicate arrival leave times ith friend respectively integer targetfriend all arrival time distinctreturn chair number friend number targetfriend sit Example 1input time 142346 targetfriend 1output 1explanation Friend 0 arrive time 1 sit chair 0 friend 1 arrive time 2 sit chair 1 friend 1 leave time 3 chair 1 friend 0 leave time 4 chair 0 friend 2 arrive time 4 sit chair 0since friend 1 sit chair 1 return 1example 2input time 3101526 targetfriend 0output 2explanation Friend 1 arrive time 1 sit chair 0 friend 2 arrive time 2 sit chair 1 friend 0 arrive time 3 sit chair 2 friend 1 leave time 5 chair 0 friend 2 leave time 6 chair 1 friend 0 leave time 10 chair 2 emptySince friend 0 sit chair 2 return 2 Constraintsn timeslength2 n 104timesilength 21 arrivali leavingi 1050 targetfriend n 1each arrivali time distinct
0array
there long thin painting represent number line the painting paint multiple overlap segment segment paint unique color you give 2D integer array segment segmentsi starti endi colori represent halfclose segment starti endi colori colorThe color overlap segment paint mix paint when color mix form new color represent set mixed colorsfor example color 2 4 6 mixed result mixed color 246for sake simplicity output sum element set setyou want describe paint minimum number nonoverlapping halfclose segment mixed color these segment represent 2D array paint paintingj leftj rightj mixj describe halfclosed segment leftj rightj mixed color sum mixjfor example paint create segment 145177 describe paint 1412477 because14 color 57 sum 12 second segments47 color 7 second segmentreturn 2d array paint describe finished painting exclude part paint you return segment ordera halfclose segment b section number line point b include point include point b example 1input segment 145477179output 14144716explanation the painting describe follow 14 color 59 sum 14 segment 47 color 79 sum 16 second segmentsExample 2input segment 17968158107output 169672478158107explanation the painting describe follow 16 color 9 segment 67 color 915 sum 24 second segment 78 color 15 second segment 810 color 7 segmentexample 3input segment 1451474714711output 14124712explanation the painting describe follow 14 color 57 sum 12 second segment 47 color 111 sum 12 fourth segmentsnote return single segment 17 incorrect mixed color set different Constraints1 segmentslength 2 104segmentsilength 31 starti endi 1051 colori 109each colori distinct
0array
there n people stand queue number 0 n 1 leave right order you give array height distinct integer heightsi represent height ith personA person person right queue everybody short more formally ith person jth person j minheightsi heightsj maxheightsi1 heightsi2 heightsj1Return array answer length n answeri number people ith person right queue Example 1input height 10685119output 312110ExplanationPerson 0 person 1 2 4person 1 person 2person 2 person 3 4Person 3 person 4Person 4 person 5Person 5 right themExample 2input height 512310output 41110 Constraintsn heightslength1 n 1051 heightsi 105all value height unique
0array
you give string s consist lowercase English letter integer kFirst convert s integer replace letter position alphabet ie replace 1 b 2 z 26 then transform integer replace sum digit Repeat transform operation k time totalFor example s zbax k 2 result integer 8 follow operationsConvert zbax 262124 262124 262124transform 1 262124 2 6 2 1 2 4 17transform 2 17 1 7 8return result integer perform operation describe Example 1input s iiii k 1output 36explanation the operation follow Convert iiii 9999 9999 9999 Transform 1 9999 9 9 9 9 36thus result integer 36example 2input s leetcode k 2output 6explanation the operation follow Convert leetcode 12552031545 12552031545 12552031545 Transform 1 12552031545 1 2 5 5 2 0 3 1 5 4 5 33 Transform 2 33 3 3 6thu result integer 6Example 3Input s zbax k 2output 8 Constraints1 slength 1001 k 10s consists lowercase english letter
2string
there survey consist n question question answer 0 1 yesthe survey give m student number 0 m 1 m mentor number 0 m 1 the answer student represent 2D integer array student studentsi integer array contain answer ith student 0indexe the answer mentor represent 2D integer array mentor mentorsj integer array contain answer jth mentor 0indexedeach student assign mentor mentor student assign the compatibility score studentmentor pair number answer student mentorfor example student answer 1 0 1 mentor answer 0 0 1 compatibility score 2 second answer sameyou task find optimal studentmentor pairing maximize sum compatibility scoresgiven student mentor return maximum compatibility score sum achieve Example 1input student 110101001 mentor 100001110output 8explanation we assign student mentor follow way student 0 mentor 2 compatibility score 3 student 1 mentor 0 compatibility score 2 student 2 mentor 1 compatibility score 3the compatibility score sum 3 2 3 8example 2input student 000000 mentor 111111output 0explanation the compatibility score studentmentor pair 0 Constraintsm studentslength mentorslengthn studentsilength mentorsjlength1 m n 8studentsik 0 1mentorsjk 0 1
0array
there n project number 0 n 1 you give integer array milestone milestonesi denote number milestone ith project hasyou work project follow rulesevery week finish exactly milestone project you work weekyou work milestone project consecutive weeksonce milestone project finish milestone work cause violate rule stop work Note able finish project milestone constraintsreturn maximum number week able work project violating rule mention Example 1input milestone 123output 6explanation one possible scenario during 1st week work milestone project 0 during 2nd week work milestone project 2 during 3rd week work milestone project 1 during 4th week work milestone project 2 during 5th week work milestone project 1 during 6th week work milestone project 2the total number week 6Example 2input milestone 521output 7Explanation one possible scenario during 1st week work milestone project 0 during 2nd week work milestone project 1 during 3rd week work milestone project 0 during 4th week work milestone project 1 during 5th week work milestone project 0 during 6th week work milestone project 2 during 7th week work milestone project 0the total number week 7note work milestone project 0 8th week violate rulesThus milestone project 0 remain unfinished Constraintsn milestoneslength1 n 1051 milestonesi 109
0array
a sequence special consist positive number 0s follow positive number 1s positive number 2sfor example 012 001112 specialIn contrast 210 1 0120 specialgiven array num consist integer 0 1 2 return number different subsequence special since answer large return modulo 109 7a subsequence array sequence derive array delete element change order remain element two subsequence different set index choose different Example 1input num 0122output 3explanation the special subsequence bolde 0122 0122 0122example 2input num 2200output 0explanation there special subsequence 2200example 3input num 012012output 7explanation the special subsequence bolde 012012 012012 012012 012012 012012 012012 012012 Constraints1 numslength 1050 numsi 2
0array
a fancy string string consecutive character equalgiven string s delete minimum possible number character s fancyreturn final string deletion it show answer unique Example 1input s leeetcodeOutput leetcodeexplanationremove e group es create leetcodeNo consecutive character equal return leetcodeExample 2input s aaabaaaaoutput aabaaexplanationremove group create aabaaaaremove second group create aabaaNo consecutive character equal return aabaaexample 3input s aaboutput aabexplanation no consecutive character equal return aab Constraints1 slength 105s consist lowercase english letter
2string
you give 0indexed 8 x 8 grid board boardrc represent cell r c game board on board free cell represent white cell represent W black cell represent BEach game consist choose free cell change color play white black however legal change cell endpoint good line horizontal vertical diagonalA good line line cell include endpoint endpoint line color remain cell middle opposite color cell line free you find example good line figure belowGiven integer rMove cMove character color represent color play white black return true change cell rmove cMove color color legal false legal Example 1input board BWWWWBBWWWBBBW rMove 4 cmove 3 color boutput trueexplanation W B represent color blue white black respectively cell rMove cMove mark XThe good line choose cell endpoint annotate red rectanglesExample 2input board bwwwbbwwb rMove 4 cmove 4 color WOutput falseexplanation while good line choose cell middle cell good line choose cell endpoint Constraintsboardlength boardrlength 80 rMove cmove 8boardrmovecmove color b w
0array
you currently design dynamic array you give 0indexed integer array num numsi number element array time in addition give integer k maximum number times resize array sizethe size array time t sizet numst need space array hold element the space waste time t define sizet numst total space waste sum space waste time t 0 t numslengthreturn minimum total space waste resize array k timesnote the array size start count number resizing operation Example 1input num 1020 k 0Output 10explanation size 2020we set initial size 20The total waste space 20 10 20 20 10example 2input num 102030 k 1Output 10explanation size 202030we set initial size 20 resize 30 time 2 the total waste space 20 10 20 20 30 30 10example 3input num 1020153020 k 2Output 15explanation size 1020203030we set initial size 10 resize 20 time 1 resize 30 time 3the total waste space 10 10 20 20 20 15 30 30 30 20 15 Constraints1 numslength 2001 numsi 1060 k numslength 1
0array
you give 0indexed string s tasked finding nonintersecte palindromic substring odd length product length maximizedmore formally want choose integer j k l 0 j k l slength substring sij skl palindrome odd length sij denote substre index index j inclusiveReturn maximum possible product length nonintersecte palindromic substringsA palindrome string forward backward a substre contiguous sequence character string Example 1input s ababbbOutput 9explanation Substrings aba bbb palindrome odd length product 3 3 9example 2input s zaaaxbbbyOutput 9explanation Substrings aaa bbb palindrome odd length product 3 3 9 constraints2 slength 105s consist lowercase english letter
2string
you give 0indexed integer array pile pilesi represent number stone ith pile integer k you apply follow operation exactly k timeschoose pilesi remove floorpilesi 2 stone itNotice apply operation pile oncereturn minimum possible total number stone remain apply k operationsfloorx greatest integer small equal x ie rounds x example 1input pile 549 k 2output 12Explanation step possible scenario apply operation pile 2 the result pile 545 apply operation pile 0 the result pile 345the total number stone 345 12example 2input pile 4367 k 3output 12Explanation step possible scenario apply operation pile 2 the result pile 4337 apply operation pile 3 the result pile 4334 apply operation pile 0 the result pile 2334the total number stone 2334 12 Constraints1 pileslength 1051 pilesi 1041 k 105
0array
you give 0indexed string s length n the string consist exactly n 2 opening bracket n 2 closing bracket a string call balanced ifIt string orIt write AB A B balanced string orIt write C C balance stringyou swap bracket index number timesreturn minimum number swap s balanced Example 1input s output 1explanation you string balanced swap index 0 index 3the result string Example 2input s output 2explanation you follow string balanced Swap index 0 index 4 s Swap index 1 index 5 s the result string Example 3input s output 0explanation the string balance Constraintsn slength2 n 106n evensi the number opening bracket equal n 2 number closing bracket equal n 2
2string
you want build obstacle course you give 0indexed integer array obstacle length n obstaclesi describe height ith obstacleFor index 0 n 1 inclusive find length long obstacle course obstacle thatyou choose number obstacle 0 inclusiveYou include ith obstacle courseYou choose obstacle order appear obstaclesEvery obstacle tall height obstacle immediately itreturn array ans length n ansi length long obstacle course index describe Example 1input obstacle 1232output 1233explanation the long valid obstacle course position 0 1 1 length 1 1 12 12 length 2 2 123 123 length 3 3 1232 122 length 3example 2input obstacle 221output 121explanation the long valid obstacle course position 0 2 2 length 1 1 22 22 length 2 2 221 1 length 1example 3input obstacle 315642output 112322explanation the long valid obstacle course position 0 3 3 length 1 1 31 1 length 1 2 315 35 length 2 15 valid 3 3156 356 length 3 156 valid 4 31564 34 length 2 14 valid 5 315642 12 length 2 Constraintsn obstacleslength1 n 1051 obstaclesi 107
0array
give array string pattern stre word return number string pattern exist substre wordA substre contiguous sequence character string example 1input pattern aabcbcd word abcOutput 3explanation appear substre abc abc appear substre abc bc appear substre abc d appear substre abc3 string pattern appear substre wordexample 2input pattern abc word aaaaabbbbbOutput 2explanation appear substre aaaaabbbbb b appear substre aaaaabbbbb c appear substre aaaaabbbbb2 string pattern appear substre wordexample 3input pattern aaa word abOutput 3explanation each pattern appear substre word ab Constraints1 patternslength 1001 patternsilength 1001 wordlength 100patternsi word consist lowercase english letter
2string
you give 0indexed array num distinct integer you want rearrange element array element rearrange array equal average neighborsMore formally rearrange array property range 1 numslength 1 numsi1 numsi1 2 equal numsireturn rearrangement num meet requirement Example 1input num 12345output 12453explanationwhen i1 numsi 2 average neighbor 14 2 25when i2 numsi 4 average neighbor 25 2 35when i3 numsi 5 average neighbor 43 2 35example 2input num 62097output 97620explanationwhen i1 numsi 7 average neighbor 96 2 75when i2 numsi 6 average neighbor 72 2 45when i3 numsi 2 average neighbor 60 2 3 constraints3 numslength 1050 numsi 105
0array
there bidirectional graph n vertex vertex label 0 n 1 inclusive the edge graph represent 2D integer array edge edgesi ui vi denote bidirectional edge vertex ui vertex vi every vertex pair connect edge vertex edge itselfyou want determine valid path exist vertex source vertex destinationgiven edge integer n source destination return true valid path source destination false Example 1input n 3 edge 011220 source 0 destination 2output trueexplanation there path vertex 0 vertex 2 0 1 2 0 2example 2input n 6 edge 0102355443 source 0 destination 5output falseexplanation there path vertex 0 vertex 5 Constraints1 n 2 1050 edgeslength 2 105edgesilength 20 ui vi n 1ui vi0 source destination n 1There duplicate edgesthere self edge
1graph
there special typewriter lowercase english letter z arrange circle pointer a character type pointer pointing character the pointer initially point character aEach second perform follow operationsmove pointer character counterclockwise clockwiseType character pointer currently ongiven string word return minimum number second type character word example 1input word abcoutput 5explanation the character print follow type character 1 second pointer initially move pointer clockwise b 1 second Type character b 1 second Move pointer clockwise c 1 second type character c 1 secondexample 2input word bzaoutput 7explanationthe character print follow Move pointer clockwise b 1 second Type character b 1 second Move pointer counterclockwise z 2 second type character z 1 second move pointer clockwise 1 second Type character 1 secondexample 3input word zjpcoutput 34explanationthe character print follow Move pointer counterclockwise z 1 second type character z 1 second move pointer clockwise j 10 second Type character j 1 second Move pointer clockwise p 6 second Type character p 1 second Move pointer counterclockwise c 13 second type character c 1 second Constraints1 wordlength 100word consist lowercase english letter
2string
you give n x n integer matrix you follow operation number timeschoose adjacent element matrix multiply 1two element consider adjacent share borderYour goal maximize summation matrixs element return maximum sum matrixs element operation mention Example 1input matrix 1111output 4explanation we follow follow step reach sum equal 4 Multiply 2 element row 1 Multiply 2 element column 1example 2input matrix 123123123output 16explanation we follow follow step reach sum equal 16 Multiply 2 element second row 1 Constraintsn matrixlength matrixilength2 n 250105 matrixij 105
0array
you city consist n intersection number 0 n 1 bidirectional road intersection the input generate reach intersection intersection road intersectionsyou give integ n 2D integer array road roadsi ui vi timei mean road intersection ui vi take timei minute travel you want know way travel intersection 0 intersection n 1 short timereturn number way arrive destination short time since answer large return modulo 109 7 Example 1input n 7 road 067012123133633351651251045462output 4explanation the short time take intersection 0 intersection 6 7 minutesthe way 7 minute 0 6 0 4 6 0 1 2 5 6 0 1 3 5 6example 2input n 2 road 1010output 1explanation there way intersection 0 intersection 1 take 10 minute Constraints1 n 200n 1 roadslength n n 1 2roadsilength 30 ui vi n 11 timei 109ui viThere road connect intersectionsyou reach intersection intersection
1graph
give integer array num return great common divisor small number large number numsthe great common divisor number large positive integer evenly divide number Example 1input num 256910output 2explanationthe small number num 2the large number num 10The great common divisor 2 10 2example 2input num 75683output 1explanationthe small number num 3the large number num 8the great common divisor 3 8 1example 3input num 33output 3explanationthe small number num 3the large number num 3the great common divisor 3 3 3 constraints2 numslength 10001 numsi 1000
0array
you give m x n integer matrix mat integer targetChoose integer row matrix absolute difference target sum choose element minimizedreturn minimum absolute differencethe absolute difference number b absolute value b example 1input mat 123456789 target 13output 0explanation one possible choice choose 1 row choose 5 second row choose 7 rowthe sum choose element 13 equal target absolute difference 0example 2input mat 123 target 100output 94explanation the good possible choice choose 1 row Choose 2 second row choose 3 rowthe sum choose element 6 absolute difference 94example 3input mat 12987 target 6output 1explanation the good choice choose 7 rowthe absolute difference 1 Constraintsm matlengthn matilength1 m n 701 matij 701 target 800
0array
you give integer n represent length unknown array try recover you give array sum contain value 2n subset sum unknown array particular orderreturn array an length n represent unknown array if multiple answer exist return themAn array sub subset array arr sub obtain arr delete possibly zero element arr the sum element sub possible subset sum arr the sum array consider 0note test case generate correct answer Example 1input n 3 sum 32100123output 123explanation 123 able achieve give subset sum sum 0 1 sum 1 2 sum 2 12 sum 3 3 sum 3 13 sum 2 23 sum 1 123 sum 0note permutation 123 permutation 123 acceptedExample 2Input n 2 sum 0000output 00explanation the correct answer 00example 3input n 4 sum 0055414991434838output 0145explanation 0145 able achieve give subset sum Constraints1 n 15sumslength 2n104 sumsi 104
0array
you give 0indexed integer array num numsi represent score ith student you give integer kPick score k student array difference highest low k score minimizedreturn minimum possible difference Example 1input num 90 k 1output 0explanation there way pick score student 90 the difference highest low score 90 90 0the minimum possible difference 0example 2input num 9417 k 2output 2explanation there way pick score student 9417 the difference highest low score 9 4 5 9417 the difference highest low score 9 1 8 9417 the difference highest low score 9 7 2 9417 the difference highest low score 4 1 3 9417 the difference highest low score 7 4 3 9417 the difference highest low score 7 1 6the minimum possible difference 2 Constraints1 k numslength 10000 numsi 105
0array
there n task assign the task time represent integer array task length n ith task take tasksi hour finish a work session work sessiontime consecutive hour breakyou finish give task way satisfie follow conditionsIf start task work session complete work sessionyou start new task immediately finish previous oneyou complete task orderGiven task sessionTime return minimum number work session need finish task follow condition abovethe test generate sessionTime great equal maximum element tasksi Example 1input task 123 sessionTime 3output 2explanation you finish task work session first work session finish second task 1 2 3 hour second work session finish task 3 hoursExample 2input task 31311 sessiontime 8output 2explanation you finish task work session first work session finish task 3 1 3 1 8 hour second work session finish task 1 hourexample 3input task 12345 sessiontime 15output 1explanation you finish task work session Constraintsn taskslength1 n 141 tasksi 10maxtasksi sessiontime 15
0array
you give binary string binary a subsequence binary consider good lead zero exception 0find number unique good subsequence binaryFor example binary 001 good subsequence 0 0 1 unique good subsequence 0 1 note subsequence 00 01 001 good lead zerosReturn number unique good subsequence binary since answer large return modulo 109 7a subsequence sequence derive sequence delete element change order remain element Example 1input binary 001output 2explanation the good subsequence binary 0 0 1the unique good subsequence 0 1example 2input binary 11output 2explanation the good subsequence binary 1 1 11the unique good subsequence 1 11example 3input binary 101Output 5explanation the good subsequence binary 1 0 1 10 11 101 the unique good subsequence 0 1 10 11 101 Constraints1 binarylength 105binary consist 0s 1s
2string
give 0indexed integer array num find leftmost middleIndex ie small possible onesA middleIndex index nums0 nums1 numsmiddleindex1 numsmiddleindex1 numsmiddleindex2 numsnumslength1If middleIndex 0 leave sum consider 0 similarly middleindex numslength 1 right sum consider 0return leftmost middleIndex satisfie condition 1 index Example 1input num 23184output 3explanation the sum number index 3 2 3 1 4the sum number index 3 4 4example 2input num 114output 2explanation the sum number index 2 1 1 0the sum number index 2 0example 3input num 25output 1explanation there valid middleindex Constraints1 numslength 1001000 numsi 1000 note this question 724 httpsleetcodecomproblemsfindpivotindex
0array
you give tree n node number 0 n 1 form parent array parent parenti parent ith node the root tree node 0 parent0 1 parent you want design datum structure allow user lock unlock upgrade node treethe data structure support follow functionsLock Locks give node give user prevent user lock node you lock node function node unlockedUnlock unlock give node give user you unlock node function currently lock userupgrade Locks give node give user unlock descendant regardless lock you upgrade node 3 condition truethe node unlockedIt lock descendant user andIt lock ancestorsimplement LockingTree classLockingTreeint parent initialize data structure parent arraylockint num int user return true possible user i d user lock node num false if possible node num lock user i d userunlockint num int user return true possible user i d user unlock node num false if possible node num unlockedupgradeint num int user return true possible user i d user upgrade node num false if possible node num upgrade Example 1inputlockingtree lock unlock unlock lock upgrade lock1 0 0 1 1 2 2 2 2 2 3 2 2 4 5 0 1 0 1outputnull true false true true true falseexplanationlockingtree lockingtree new LockingTree1 0 0 1 1 2 2lockingtreelock2 2 return true node 2 unlock Node 2 locked user 2lockingTreeunlock2 3 return false user 3 unlock node lock user 2lockingTreeunlock2 2 return true node 2 previously lock user 2 Node 2 unlockedlockingtreelock4 5 return true node 4 unlock Node 4 lock user 5lockingTreeupgrade0 1 return true node 0 unlocked lock descendant node 4 Node 0 lock user 1 node 4 unlockedlockingtreelock0 1 return false node 0 lock Constraintsn parentlength2 n 20000 parenti n 1 0parent0 10 num n 11 user 104parent represent valid treeat 2000 call total lock unlock upgrade
1graph
you give integer array num we subset num good product represent product distinct prime numbersfor example num 1 2 3 42 3 1 2 3 1 3 good subset product 6 23 6 23 3 3 respectively1 4 4 good subset product 4 22 4 22 respectivelyreturn number different good subset num modulo 109 7A subset num array obtain delete possibly element num two subset different choose index delete different Example 1input num 1234output 6explanation the good subset 12 product 2 product distinct prime 2 123 product 6 product distinct prime 2 3 13 product 3 product distinct prime 3 2 product 2 product distinct prime 2 23 product 6 product distinct prime 2 3 3 product 3 product distinct prime 3example 2input num 42315output 5explanation the good subset 2 product 2 product distinct prime 2 23 product 6 product distinct prime 2 3 215 product 30 product distinct prime 2 3 5 3 product 3 product distinct prime 3 15 product 15 product distinct prime 3 5 constraints1 numslength 1051 numsi 30
0array
give 0indexed integer array num return number distinct quadruplet b c d thatnumsa numsb numsc numsd anda b c d Example 1input num 1236output 1explanation the quadruplet satisfie requirement 0 1 2 3 1 2 3 6example 2input num 33645output 0explanation there quadruplet 33645example 3input num 11135output 4explanation the 4 quadruplet satisfy requirement 0 1 2 3 1 1 1 3 0 1 3 4 1 1 3 5 0 2 3 4 1 1 3 5 1 2 3 4 1 1 3 5 constraints4 numslength 501 numsi 100
0array
you play game contain multiple character character main property attack defense you give 2D integer array property propertiesi attacki defensei represent property ith character gameA character say weak character attack defense level strictly great character attack defense level more formally character say weak exist character j attackj attacki defensej defenseiReturn number weak character example 1input property 556336output 0explanation no character strictly great attack defense otherexample 2input property 2233output 1explanation the character weak second character strictly great attack defenseexample 3input property 1510443output 1explanation the character weak second character strictly great attack defense constraints2 propertieslength 105propertiesilength 21 attacki defensei 105
0array
there n room need visit label 0 n 1 each day label start 0 you visit room dayinitially day 0 visit room 0 the order visit room come day determine follow rule give 0indexed array nextvisit length nAssuming day visit room iif room odd number time include current visit day visit room low equal room number specify nextVisiti 0 nextVisiti iif room number time include current visit day visit room 1 mod nReturn label day room it show day exist since answer large return modulo 109 7 Example 1input nextVisit 00output 2explanation on day 0 visit room 0 the total time room 0 1 odd on day visit room nextvisit0 0 on day 1 visit room 0 the total time room 0 2 on day visit room 0 1 mod 2 1 on day 2 visit room 1 this day roomsExample 2input nextVisit 002output 6explanationyour room visit order day 0010012day 6 day roomsExample 3input nextvisit 0120output 6explanationyour room visit order day 0011223day 6 day room Constraintsn nextvisitlength2 n 1050 nextVisiti
0array
you give integer array num perform follow operation number time numsswap position element numsi numsj gcdnumsi numsj 1 gcdnumsi numsj great common divisor numsi numsjreturn true possible sort num nondecrease order swap method false Example 1input num 7213output trueexplanation we sort 7213 perform follow operation Swap 7 21 gcd721 7 num 2173 Swap 21 3 gcd213 3 num 3721example 2input num 5262output falseexplanation it impossible sort array 5 swap elementExample 3input num 1059315Output trueWe sort 1059315 perform follow operation Swap 10 15 gcd1015 5 num 1559310 Swap 15 3 gcd153 3 num 3591510 Swap 10 15 gcd1015 5 num 3591015 Constraints1 numslength 3 1042 numsi 105
0array
give 0indexed string word character ch reverse segment word start index 0 end index occurrence ch inclusive if character ch exist word nothingFor example word abcdefd ch d reverse segment start 0 end 3 inclusive the result string dcbaefdreturn result string example 1input word abcdefd ch doutput dcbaefdexplanation the occurrence d index 3 Reverse word 0 3 inclusive result string dcbaefdExample 2input word xyxzxe ch zOutput zxyxxeexplanation the occurrence z index 3reverse word 0 3 inclusive result stre zxyxxeexample 3input word abcd ch zOutput abcdExplanation z exist wordYou reverse operation result string abcd Constraints1 wordlength 250word consist lowercase english lettersch lowercase english letter
2string
you give n rectangle represent 0indexed 2D integer array rectangle rectanglesi widthi heighti denote width height ith rectangleTwo rectangle j j consider interchangeable widthtoheight ratio more formally rectangle interchangeable widthiheighti widthjheightj decimal division integer divisionReturn number pair interchangeable rectangle rectangle example 1input rectangle 483610201530output 6explanation the following interchangeable pair rectangle index 0indexe rectangle 0 rectangle 1 48 36 Rectangle 0 rectangle 2 48 1020 Rectangle 0 rectangle 3 48 1530 Rectangle 1 rectangle 2 36 1020 Rectangle 1 rectangle 3 36 1530 Rectangle 2 rectangle 3 1020 1530example 2input rectangle 4578output 0explanation there interchangeable pair rectangle Constraintsn rectangleslength1 n 105rectanglesilength 21 widthi heighti 105
0array
give string s find disjoint palindromic subsequence s product length maximize the subsequence disjoint pick character indexReturn maximum possible product length palindromic subsequencesA subsequence string derive string delete character change order remain character a string palindromic read forward backward Example 1input s leetcodecomOutput 9explanation an optimal solution choose ete 1st subsequence cdc 2nd subsequencethe product length 3 3 9example 2input s bbOutput 1explanation an optimal solution choose b character 1st subsequence b second character 2nd subsequencethe product length 1 1 1example 3input s accbcaxxcxxoutput 25explanation an optimal solution choose accca 1st subsequence xxcxx 2nd subsequencethe product length 5 5 25 constraints2 slength 12 consists lowercase english letter
2string
there family tree root 0 consist n node number 0 n 1 you give 0indexed integer array parent parentsi parent node since node 0 root parents0 1There 105 genetic value represent integer inclusive range 1 105 you give 0indexed integer array num numsi distinct genetic value node iReturn array an length n ansi small genetic value miss subtree root node iThe subtree root node x contain node x descendant node Example 1input parent 1002 num 1234output 5111explanation the answer subtree calculate follow 0 the subtree contain node 0123 value 1234 5 small miss value 1 the subtree contain node 1 value 2 1 small miss value 2 the subtree contain node 23 value 34 1 small miss value 3 the subtree contain node 3 value 4 1 small miss valueexample 2input parent 101033 num 546213output 711421explanation the answer subtree calculate follow 0 the subtree contain node 012345 value 546213 7 small miss value 1 the subtree contain node 12 value 46 1 small miss value 2 the subtree contain node 2 value 6 1 small miss value 3 the subtree contain node 345 value 213 4 small miss value 4 the subtree contain node 4 value 1 2 small miss value 5 the subtree contain node 5 value 3 1 small miss valueexample 3input parent 1230241 num 2345678output 1111111explanation the value 1 miss subtree Constraintsn parentslength numslength2 n 1050 parentsi n 1 0parents0 1parents represent valid tree1 numsi 105each numsi distinct
1graph
give integer array num integer k return number pair j j numsi numsj kThe value x define asx x 0x x 0 example 1input num 1221 k 1output 4explanation the pair absolute difference 1 1221 1221 1221 1221example 2input num 13 k 3output 0explanation there pair absolute difference 3example 3input num 32154 k 2output 3explanation the pair absolute difference 2 32154 32154 32154 Constraints1 numslength 2001 numsi 1001 k 99
0array
an integer array original transformed double array change append twice value element original randomly shuffle result arrayGiven array change return original change double array if change double array return array the element original return order Example 1input change 134268output 134explanation one possible original array 134 Twice value 1 1 2 2 Twice value 3 3 2 6 Twice value 4 4 2 8other original array 431 314example 2input change 6301output Explanation change double arrayExample 3input change 1Output Explanation change double array Constraints1 changedlength 1050 changedi 105
0array
there n point road drive taxi the n point road label 1 n direction go want drive point 1 point n money pick passenger you change direction taxithe passenger represent 0indexed 2D integer array ride ridesi starti endi tipi denote ith passenger request ride point starti point endi willing tipi dollar tipfor passenger pick earn endi starti tipi dollar you drive passenger timeGiven n ride return maximum number dollar earn pick passenger optimallynote you drop passenger pick different passenger point Example 1input n 5 ride 254151output 7explanation we pick passenger 0 earn 5 2 4 7 dollarsexample 2input n 20 ride 161310210123111221215213181output 20explanation we pick follow passenger drive passenger 1 point 3 point 10 profit 10 3 2 9 dollar drive passenger 2 point 10 point 12 profit 12 10 3 5 dollar drive passenger 5 point 13 point 18 profit 18 13 1 6 dollarsWe earn 9 5 6 20 dollar total Constraints1 n 1051 rideslength 3 104ridesilength 31 starti endi n1 tipi 105
0array
you give integer array num in operation replace element num integernum consider continuous follow condition fulfilledall element num uniquethe difference maximum element minimum element num equal numslength 1for example num 4 2 5 3 continuous num 1 2 3 5 6 continuousreturn minimum number operation num continuous Example 1input num 4253output 0explanation num continuousexample 2input num 12356output 1explanation one possible solution change element 4the result array 12354 continuousexample 3input num 1101001000output 3explanation one possible solution Change second element 2 Change element 3 Change fourth element 4the result array 1234 continuous Constraints1 numslength 1051 numsi 109
0array
you give 0indexed integer array num for index 1 numslength 2 beauty numsi equals2 numsj numsi numsk 0 j k numslength 11 numsi 1 numsi numsi 1 previous condition satisfied0 previous condition holdsReturn sum beauty numsi 1 numslength 2 Example 1input num 123output 2explanation for index range 1 1 the beauty nums1 equal 2example 2input num 2464output 1explanation for index range 1 2 the beauty nums1 equal 1 the beauty nums2 equal 0example 3input num 321output 0explanation for index range 1 1 the beauty nums1 equal 0 constraints3 numslength 1051 numsi 105
0array
you give stream point XY plane Design algorithm thatadd new point stream data structure Duplicate point allow treat different pointsgiven query point count number way choose point data structure point query point form axisaligne square positive areaan axisaligne square square edge length parallel perpendicular xaxis yaxisimplement DetectSquares classdetectsquare Initializes object datum structurevoid addint point add new point point x y data structureint countint point count number way form axisaligne square point point x y describe Example 1inputdetectsquares add add add count count add count 3 10 11 2 3 2 11 10 14 8 11 2 11 10outputnull null null null 1 0 null 2explanationdetectsquares detectsquare new DetectSquaresdetectSquaresadd3 10detectSquaresadd11 2detectsquaresadd3 2detectsquarescount11 10 return 1 you choose the second pointsdetectsquarescount14 8 return 0 the query point form square point datum structuredetectSquaresadd11 2 add duplicate point alloweddetectsquarescount11 10 return 2 you choose the second point the fourth point Constraintspointlength 20 x y 1000at 3000 call total add count
0array
you give stre s length n integer k you tasked find long subsequence repeat k time string sA subsequence string derive string delete character change order remain charactersA subsequence seq repeat k time string s seq k subsequence s seq k represent string construct concatenate seq k timesFor example bba repeat 2 time stre bababcba string bbabba construct concatenate bba 2 time subsequence stre bababcbareturn long subsequence repeat k time string s if multiple subsequence find return lexicographically large if subsequence return string Example 1input s letsleetcode k 2output letexplanation there long subsequence repeat 2 time let etelet lexicographically large oneexample 2input s bb k 2output bExplanation the long subsequence repeat 2 time bExample 3input s ab k 2Output Explanation there subsequence repeat 2 time empty string return Constraintsn slength2 n k 20002 n k 8s consists lowercase english letter
2string
give 0indexed integer array num size n find maximum difference numsi numsj ie numsj numsi 0 j n numsi numsjreturn maximum difference if j exist return 1 example 1input num 7154output 4explanationthe maximum difference occur 1 j 2 numsj numsi 5 1 4note 1 j 0 difference numsj numsi 7 1 6 j validExample 2input num 9432output 1explanationthere j j numsi numsjExample 3input num 15210output 9explanationthe maximum difference occur 0 j 3 numsj numsi 10 1 9 Constraintsn numslength2 n 10001 numsi 109
0array
you give 0indexed 2d array grid size 2 x n gridrc represent number point position r c matrix two robot playing game matrixBoth robot initially start 0 0 want reach 1 n1 each robot right r c r c 1 r c r 1 cAt start game robot move 0 0 1 n1 collecting point cell path for cell r c traverse path gridrc set 0 then second robot move 0 0 1 n1 collecting point path Note path intersect anotherthe robot want minimize number point collect second robot in contrast second robot want maximize number point collect if robot play optimally return number point collect second robot Example 1input grid 254151output 4explanation the optimal path take robot show red optimal path take second robot show blueThe cell visit robot set 0the second robot collect 0 0 4 0 4 pointsExample 2input grid 331852output 4explanation the optimal path take robot show red optimal path take second robot show blueThe cell visit robot set 0the second robot collect 0 3 1 0 4 pointsExample 3input grid 131151331output 7explanation the optimal path take robot show red optimal path take second robot show blueThe cell visit robot set 0the second robot collect 0 1 3 3 0 7 point constraintsgridlength 2n gridrlength1 n 5 1041 gridrc 105
0array
you give m x n matrix board represent current state crossword puzzle the crossword contain lowercase english letter solve word represent cell represent block cellsA word place horizontally leave right right leave vertically board ifit occupy cell contain character the cell letter place match letter boardThere cell lowercase letter directly leave right word word place horizontallythere cell lowercase letter directly word word place verticallygiven string word return true word place board false Example 1input board c word abcoutput trueexplanation the word abc place show bottomExample 2input board c word acOutput falseexplanation it impossible place word spaceletter itExample 3input board c word caoutput trueexplanation the word place show right leave Constraintsm boardlengthn boardilength1 m n 2 105boardij lowercase english letter1 wordlength maxm nword contain lowercase english letter
0array
you give 0indexed 1dimensional 1d integer array original integer m n you task create 2dimensional 2d array m row n column element originalthe element indice 0 n 1 inclusive original form row construct 2D array element index n 2 n 1 inclusive form second row construct 2D array onReturn m x n 2D array construct accord procedure 2D array impossible Example 1input original 1234 m 2 n 2output 1234explanation the construct 2D array contain 2 row 2 columnsthe group n2 element original 12 row construct 2D arraythe second group n2 element original 34 second row construct 2D arrayExample 2Input original 123 m 1 n 3output 123explanation the constructed 2D array contain 1 row 3 columnsput element original row construct 2D arrayExample 3Input original 12 m 1 n 1output Explanation there 2 element originalit impossible fit 2 element 1x1 2D array return 2D array Constraints1 originallength 5 1041 originali 1051 m n 4 104
0array
a teacher write test n truefalse question t denote true F denote false he want confuse student maximize number consecutive question answer multiple true multiple false rowyou give string answerkey answerKeyi original answer ith question in addition give integer k maximum number time perform follow operationchange answer key question t F ie set answerKeyi T FReturn maximum number consecutive Ts Fs answer key perform operation k time Example 1input answerkey ttff k 2output 4explanation we replace Fs Ts answerkey TTTTThere consecutive TsExample 2input answerkey TFFT k 1Output 3explanation we replace T F answerkey FFFTAlternatively replace second t F answerkey TFFFIn case consecutive FsExample 3input answerkey ttfttftt k 1output 5explanation we replace F answerKey tttttfttalternatively replace second F answerkey TTFTTTTT in case consecutive Ts Constraintsn answerkeylength1 n 5 104answerkeyi T f1 k n
2string
you give 0indexed integer array num length n the number way partition num number pivot index satisfy conditions1 pivot nnums0 nums1 numspivot 1 numspivot numspivot 1 numsn 1you give integer k you choose change value element num k leave array unchangedreturn maximum possible number way partition num satisfy condition change element Example 1input num 212 k 3output 1explanation one optimal approach change nums0 k the array 312there way partition array for pivot 2 partition 31 2 3 1 2example 2input num 000 k 1output 2explanation the optimal approach leave array unchangedthere way partition array for pivot 1 partition 0 00 0 0 0 for pivot 2 partition 00 0 0 0 0example 3input num 22425201515167191001314 k 33output 4explanation one optimal approach change nums2 k the array 22433201515167191001314there way partition array Constraintsn numslength2 n 105105 k numsi 105
0array
you give string s consist n character X OA define select consecutive character s convert O note apply character o stay samereturn minimum number move require character s convert O Example 1input s xxxoutput 1explanation XXX OOOWe select 3 character convert moveExample 2input s XXOXOutput 2explanation XXOX OOOX OOOOWe select 3 character convert OThen select 3 character convert final string contain OsExample 3Input s OOOOOutput 0explanation there Xs s convert Constraints3 slength 1000si x o
2string
you observation n m 6side dice roll face number 1 6 n observation go miss observation m roll fortunately calculate average value n m rollsyou give integer array roll length m rollsi value ith observation you give integer mean nReturn array length n contain miss observation average value n m roll exactly mean if multiple valid answer return if array exist return arraythe average value set k number sum number divide kNote mean integer sum n m roll divisible n m Example 1input roll 3243 mean 4 n 2output 66explanation the mean n m roll 3 2 4 3 6 6 6 4example 2input roll 156 mean 3 n 4output 2322explanation the mean n m roll 1 5 6 2 3 2 2 7 3example 3input roll 1234 mean 6 n 4Output Explanation it impossible mean 6 matter 4 miss roll Constraintsm rollslength1 n m 1051 rollsi mean 6
0array
Alice Bob continue game stone there row n stone stone associate value you give integer array stone stonesi value ith stoneAlice Bob turn Alice start on turn player remove stone stone the player remove stone lose sum value remove stone divisible 3 Bob win automatically remain stone Alices turnassuming player play optimally return true Alice win false Bob win Example 1input stone 21output trueexplanation the game play follow turn 1 Alice remove stone turn 2 Bob remove remain stone the sum remove stone 1 2 3 divisible 3 therefore Bob lose Alice win gameexample 2input stone 2output falseexplanation Alice remove stone sum value remove stone 2 since stone remove sum value divisible 3 Bob win gameexample 3input stone 51243output falseexplanation Bob win one possible way Bob win show turn 1 Alice remove second stone value 1 Sum remove stone 1 turn 2 Bob remove fifth stone value 3 Sum remove stone 1 3 4 turn 3 alice remove fourth stone value 4 Sum remove stone 1 3 4 8 turn 4 Bob remove stone value 2 Sum remove stone 1 3 4 2 10 turn 5 Alice remove stone value 5 Sum remove stone 1 3 4 2 5 15alice lose game sum remove stone 15 divisible 3 Bob win game Constraints1 stoneslength 1051 stonesi 104
0array
you give string s integer k letter letter integer repetitionReturn lexicographically smallest subsequence s length k letter letter appear repetition time the test case generate letter appear s repetition timesA subsequence string derive string delete character change order remain charactersA stre lexicographically small string b position b differ string letter appear early alphabet corresponding letter b example 1input s leet k 3 letter e repetition 1output eetExplanation there subsequence length 3 letter e appear 1 time lee leet let leet let leet eet leetthe lexicographically smallest subsequence eetExample 2input s leetcode k 4 letter e repetition 2output ecdeexplanation ecde lexicographically small subsequence length 4 letter e appear 2 timesexample 3input s bb k 2 letter b repetition 2Output bbexplanation bb subsequence length 2 letter b appear 2 time Constraints1 repetition k slength 5 104s consist lowercase english lettersletter lowercase english letter appear s repetition time
2string
give integer array nums1 nums2 nums3 return distinct array contain value present array you return value order Example 1input nums1 1132 nums2 23 nums3 3output 32explanation the value present arrays 3 array 2 nums1 nums2Example 2input nums1 31 nums2 23 nums3 12output 231explanation the value present arrays 2 nums2 nums3 3 nums1 nums2 1 nums1 nums3example 3input nums1 122 nums2 433 nums3 5output Explanation no value present array constraints1 nums1length nums2length nums3length 1001 nums1i nums2j nums3k 100
0array
you give 2D integer grid size m x n integer x in operation add x subtract x element gridA univalue grid grid element equalreturn minimum number operation grid univalue if possible return 1 example 1input grid 2468 x 2output 4explanation we element equal 4 follow Add x 2 Subtract x 6 Subtract x 8 twicea total 4 operation usedexample 2input grid 1523 x 1output 5explanation we element equal 3example 3input grid 1234 x 2output 1explanation it impossible element equal Constraintsm gridlengthn gridilength1 m n 1051 m n 1051 x gridij 104
0array
you give integer array num 2 n integer you need partition num array length n minimize absolute difference sum array to partition num element num arraysreturn minimum possible absolute difference Example 1input num 3973output 2explanation one optimal partition 39 73the absolute difference sum array abs3 9 7 3 2example 2input num 3636output 72explanation one optimal partition 36 36the absolute difference sum array abs36 36 72example 3input num 210429output 0explanation one optimal partition 249 102the absolute difference sum array abs2 4 9 1 0 2 0 Constraints1 n 15numslength 2 n107 numsi 107
0array
there n seat n student room you give array seat length n seatsi position ith seat you give array student length n studentsj position jth studentyou perform follow number timesincrease decrease position ith student 1 ie move ith student position x x 1 x 1return minimum number move require student seat student seatnote multiple seat student position begin Example 1input seat 315 student 274output 4explanation the student move follow the student move position 2 position 1 1 the second student move position 7 position 5 2 move the student move position 4 position 3 1 movein total 1 2 1 4 move usedexample 2input seat 4159 student 1326output 7explanation the student move follow the student move the second student move position 3 position 4 1 the student move position 2 position 5 3 move the fourth student move position 6 position 9 3 movesIn total 0 1 3 3 7 move usedexample 3input seat 2266 student 1326output 4explanation Note seat position 2 seat position 6the student move follow the student move position 1 position 2 1 the second student move position 3 position 6 3 move the student move the fourth student movedIn total 1 3 0 0 4 move Constraintsn seatslength studentslength1 n 1001 seatsi studentsj 100
0array
there n piece arrange line piece color a b you give string color length n colorsi color ith pieceAlice Bob playing game alternating turn remove piece line in game Alice move firstAlice allow remove piece color a neighbor color A she allow remove piece color BBob allow remove piece color b neighbor color b he allow remove piece color AAlice Bob remove piece edge lineif player turn player lose player winsAssuming Alice Bob play optimally return true Alice win return false Bob win Example 1input color AAABABBOutput trueexplanationaaababb AABABBAlice move firstshe remove second a leave a neighbor ANow Bobs turnBob turn Bs neighbor BThus Alice win return trueexample 2input color aaoutput falseexplanationalice turn firstthere as edge line turnthu Bob win return falseexample 3input color ABBBBBBBAAAOutput falseexplanationabbbbbbbaaa ABBBBBBBAAAlice move firsther option remove second a rightabbbbbbbaa ABBBBBBAANext Bobs turnHe option b piece remove he pick anyOn alice second turn piece removeThus Bob win return false Constraints1 colorslength 105colors consist letter a b
2string
give sorted 0indexed integer array nums1 nums2 integer k return kth 1based small product nums1i nums2j 0 nums1length 0 j nums2length Example 1input nums1 25 nums2 34 k 2output 8explanation the 2 small product nums10 nums20 2 3 6 nums10 nums21 2 4 8the 2nd small product 8example 2input nums1 4203 nums2 24 k 6output 0explanation the 6 small product nums10 nums21 4 4 16 nums10 nums20 4 2 8 nums11 nums21 2 4 8 nums11 nums20 2 2 4 nums12 nums20 0 2 0 nums12 nums21 0 4 0the 6th small product 0example 3input nums1 21012 nums2 31245 k 3output 6explanation the 3 small product nums10 nums24 2 5 10 nums10 nums23 2 4 8 nums14 nums20 2 3 6the 3rd small product 6 Constraints1 nums1length nums2length 5 104105 nums1i nums2j 1051 k nums1length nums2lengthnums1 nums2 sort
0array
a sentence list token separate single space lead trailing space every token positive number consist digits 09 lead zero word consist lowercase English lettersfor example puppy 2 eye 4 leg sentence seven token 2 4 number tokens puppy wordsgiven stre s represent sentence need check number s strictly increase left right ie number number strictly small number right sReturn true false example 1input s 1 box 3 blue 4 red 6 green 12 yellow marblesoutput trueexplanation the number s 1 3 4 6 12they strictly increase leave right 1 3 4 6 12example 2input s hello world 5 x 5output falseexplanation the number s 5 5 they strictly increasingExample 3input s sunset 7 51 pm overnight low low 50 60 soutput falseexplanation the number s 7 51 50 60 they strictly increase Constraints3 slength 200s consist lowercase english letter space digit 0 9 inclusivethe number token s 2 100 inclusivethe token s separate single spacethere number sEach number s positive number 100 lead zeross contain lead trail space
2string
you task write program popular bank automate incoming transaction transfer deposit withdraw the bank n account number 1 n the initial balance account store 0indexed integer array balance 1th account have initial balance balanceiexecute valid transaction a transaction valid ifthe give account number 1 n andthe money withdraw transfer equal balance accountimplement Bank classbanklong balance Initializes object 0indexe integer array balanceboolean transferint account1 int account2 long money transfer money dollar account number account1 account number account2 return true transaction successful false otherwiseboolean depositint account long money deposit money dollar account number account return true transaction successful false otherwiseboolean withdrawint account long money withdraw money dollar account number account return true transaction successful false example 1inputbank withdraw transfer deposit transfer withdraw10 100 20 50 30 3 10 5 1 20 5 20 3 4 15 10 50outputnull true true true false falseExplanationBank bank new Bank10 100 20 50 30bankwithdraw3 10 return true account 3 balance 20 valid withdraw 10 account 3 20 10 10banktransfer5 1 20 return true account 5 balance 30 valid transfer 20 account 5 30 20 10 account 1 10 20 30bankdeposit5 20 return true valid deposit 20 account 5 account 5 10 20 30banktransfer3 4 15 return false current balance account 3 10 invalid transfer 15 itbankwithdraw10 50 return false invalid account 10 exist Constraintsn balancelength1 n account account1 account2 1050 balancei money 1012at 104 call function transfer deposit withdraw
0array
give integer array num find maximum possible bitwise or subset num return number different nonempty subset maximum bitwise ORAn array subset array b obtain b delete possibly zero element b two subset consider different index element choose differentThe bitwise or array equal a0 or a1 or or aalength 1 0indexed Example 1input num 31output 2explanation the maximum possible bitwise or subset 3 there 2 subset bitwise or 3 3 31example 2input num 222output 7explanation all nonempty subset 222 bitwise or 2 there 23 1 7 total subsetsexample 3input num 3215output 6explanation the maximum possible bitwise or subset 7 there 6 subset bitwise or 7 35 315 325 3215 25 215 constraints1 numslength 161 numsi 105
0array
a city represent bidirectional connect graph n vertex vertex label 1 n inclusive the edge graph represent 2D integer array edge edgesi ui vi denote bidirectional edge vertex ui vertex vi every vertex pair connect edge vertex edge the time take traverse edge time minutesEach vertex traffic signal change color green red vice versa change minute all signal change time you enter vertex time leave vertex signal green you wait vertex signal greenthe second minimum value define small value strictly large minimum valuefor example second minimum value 2 3 4 3 second minimum value 2 2 4 4given n edge time change return second minimum time vertex 1 vertex nnotesyou vertex number time include 1 nYou assume journey start signal turn green Example 1input n 5 edge 1213143445 time 3 change 5output 13explanationthe figure leave show give graphThe blue path figure right minimum time pathThe time take Start 1 time elapsed0 1 4 3 minute time elapsed3 4 5 3 minute time elapsed6hence minimum time need 6 minutesthe red path show path second minimum time Start 1 time elapsed0 1 3 3 minute time elapsed3 3 4 3 minute time elapsed6 wait 4 4 minute time elapsed10 4 5 3 minute time elapsed13hence second minimum time 13 minute Example 2input n 2 edge 12 time 3 change 2output 11explanationthe minimum time path 1 2 time 3 minutesthe second minimum time path 1 2 1 2 time 11 minute Constraints2 n 104n 1 edgeslength min2 104 n n 1 2edgesilength 21 ui vi nui vithere duplicate edgeseach vertex reach directly indirectly vertex1 time change 103
1graph
a sentence consist lowercase letter z digit 0 9 hyphens punctuation mark space each sentence break tokens separate space a token valid word follow trueIt contain lowercase letter hyphens andor punctuation digitsthere hyphen if present surround lowercase character ab valid ab ab validThere punctuation mark if present end token ab cd valid ab c validexample valid word include ab afad bac give string sentence return number valid word sentence Example 1input sentence cat dogoutput 3explanation the valid word sentence cat dogExample 2input sentence 1s b8doutput 0explanation there valid word sentencethis invalid start punctuation mark1s b8d invalid contain digitsexample 3input sentence alice bob playing stonegame10output 5explanation the valid word sentence alice bob playingstonegame10 invalid contain digits Constraints1 sentencelength 1000sentence contain lowercase english letter digit there 1 token
2string
you give integer n indicate n course label 1 n you give 2D integer array relations relationsj prevCoursej nextCoursej denote course prevCoursej complete course nextCoursej prerequisite relationship furthermore give 0indexed integer array time timei denote month take complete i1th courseYou find minimum number month need complete course follow rulesyou start take course time prerequisite metany number course take timereturn minimum number month need complete coursesNote the test case generate possible complete course ie graph direct acyclic graph Example 1input n 3 relation 1323 time 325output 8explanation the figure represent give graph time require complete course we start course 1 course 2 simultaneously month 0course 1 take 3 month course 2 take 2 month complete respectivelythus early time start course 3 month 3 total time require 3 5 8 monthsexample 2input n 5 relation 1525353445 time 12345output 12explanation the figure represent give graph time require complete courseyou start course 1 2 3 month 0you complete 1 2 3 month respectivelycourse 4 take course 3 complete ie 3 month it complete 3 4 7 monthscourse 5 take course 1 2 3 4 complete ie max1237 7 monthsThus minimum time need complete course 7 5 12 month Constraints1 n 5 1040 relationslength minn n 1 2 5 104relationsjlength 21 prevCoursej nextCoursej nprevCoursej nextcoursejall pair prevCoursej nextCoursej uniquetimelength n1 timei 104the give graph direct acyclic graph
1graph
you give 0indexed 2d integer array event eventsi startTimei endTimei valuei the ith event start startTimei end endTimei attend event receive value valuei you choose nonoverlapping event attend sum value maximizedreturn maximum sumnote start time end time inclusive attend event start end time more specifically attend event end time t event start t 1 example 1input event 132452243output 4explanation choose green event 0 1 sum 2 2 4example 2input event 132452155output 5explanation Choose event 2 sum 5example 3input event 153151665output 8explanation choose event 0 2 sum 3 5 8 constraints2 eventslength 105eventsilength 31 startTimei endTimei 1091 valuei 106
0array
give 0indexed integer array num return small index num mod 10 numsi 1 index existx mod y denote remainder x divide y Example 1input num 012output 0explanation i0 0 mod 10 0 nums0i1 1 mod 10 1 nums1i2 2 mod 10 2 nums2all index mod 10 numsi return small index 0example 2input num 4321output 2explanation i0 0 mod 10 0 nums0i1 1 mod 10 1 nums1i2 2 mod 10 2 nums2i3 3 mod 10 3 nums32 index mod 10 numsiExample 3input num 1234567890output 1explanation no index satisfy mod 10 numsi Constraints1 numslength 1000 numsi 9
0array
an original string consist lowercase English letter encode following stepsarbitrarily split sequence number nonempty substringsarbitrarily choose element possibly sequence replace length numeric stringconcatenate sequence encode stringfor example way encode original string abcdefghijklmnop besplit sequence ab cdefghijklmn o pChoose second element replace length respectively the sequence ab 12 1 pConcatenate element sequence encode string ab121pGiven encode string s1 s2 consist lowercase English letter digit 19 inclusive return true exist original string encode s1 s2 otherwise return falseNote the test case generate number consecutive digit s1 s2 exceed 3 Example 1input s1 internationalization s2 i18noutput trueexplanation it possible internationalization original string internationalization Split internationalization do replace element Concatenate internationalization s1 internationalization Split nternationalizatio n replace 18 n Concatenate i18n s2example 2input s1 l123e s2 44output trueexplanation it possible leetcode original string leetcode Split l e et cod e replace l 1 2 3 e Concatenate l123e s1 leetcode Split leet code replace 4 4 Concatenate 44 s2example 3input s1 a5b s2 c5boutput falseexplanation it impossible the original string encode s1 start letter the original string encode s2 start letter c constraints1 s1length s2length 40s1 s2 consist digit 19 inclusive lowercase english letter onlythe number consecutive digit s1 s2 exceed 3
2string
a substre contiguous nonempty sequence character stringa vowel substre substring consist vowel e o u vowel present itgiven string word return number vowel substring word example 1input word aeiouuoutput 2explanation the vowel substring word follow underlined aeiouu aeiouuExample 2input word unicornarihanoutput 0explanation not 5 vowel present vowel substringsExample 3input word cuaieuouacOutput 7explanation the vowel substring word follow underlined cuaieuouac cuaieuouac cuaieuouac cuaieuouac cuaieuouac cuaieuouac cuaieuouac Constraints1 wordlength 100word consist lowercase english letter
2string
give string word return sum number vowel e o u substre wordA substre contiguous nonempty sequence character stringnote due large constraint answer fit sign 32bit integer please careful calculation example 1input word abaoutput 6explanation all possible substring ab aba b ba b 0 vowel ab ba 1 vowel aba 2 vowel ithence total sum vowel 0 1 1 1 1 2 6 Example 2input word abcoutput 3explanation all possible substring ab abc b bc c ab abc 1 vowel b bc c 0 vowel eachhence total sum vowel 1 1 1 0 0 0 3example 3input word ltcdoutput 0explanation there vowel substre ltcd Constraints1 wordlength 105word consist lowercase english letter
2string
you give integer n indicate n specialty retail store there m product type vary amount give 0indexed integer array quantity quantitiesi represent number product ith product typeyou need distribute product retail store follow rulesa store give product type give itaft distribution store give number product possibly 0 let x represent maximum number product give store you want x small possible ie want minimize maximum number product give storereturn minimum possible x example 1input n 6 quantity 116output 3explanation one optimal way the 11 product type 0 distribute store amount 2 3 3 3 the 6 product type 1 distribute store amount 3 3the maximum number product give store max2 3 3 3 3 3 3example 2input n 7 quantity 151010output 5explanation one optimal way the 15 product type 0 distribute store amount 5 5 5 the 10 product type 1 distribute store amount 5 5 the 10 product type 2 distribute store amount 5 5the maximum number product give store max5 5 5 5 5 5 5 5example 3input n 1 quantity 100000output 100000explanation the optimal way the 100000 product type 0 distribute storeThe maximum number product give store max100000 100000 Constraintsm quantitieslength1 m n 1051 quantitiesi 105
0array
two string word1 word2 consider equivalent difference frequency letter z word1 word2 3given string word1 word2 length n return true word1 word2 equivalent false otherwisethe frequency letter x number time occur stre example 1input word1 aaaa word2 bccboutput falseexplanation there 4 aaaa 0 bccbthe difference 4 allow 3example 2input word1 abcdeef word2 abaaaccoutput trueexplanation the difference frequency letter word1 word2 3 appear 1 time word1 4 time word2 the difference 3 b appear 1 time word1 1 time word2 the difference 0 c appear 1 time word1 2 time word2 the difference 1 d appear 1 time word1 0 time word2 the difference 1 e appear 2 time word1 0 time word2 the difference 2 f appear 1 time word1 0 time word2 the difference 1example 3input word1 cccddabba word2 bababababoutput trueexplanation the difference frequency letter word1 word2 3 appear 2 time word1 4 time word2 the difference 2 b appear 2 time word1 5 time word2 the difference 3 c appear 3 time word1 0 time word2 the difference 3 d appear 2 time word1 0 time word2 the difference 2 Constraintsn word1length word2length1 n 100word1 word2 consist lowercase english letter
2string
you give 2D integer array item itemsi pricei beautyi denote price beauty item respectivelyYou give 0indexed integer array query for queriesj want determine maximum beauty item price equal queriesj if item exist answer query 0return array answer length query answerj answer jth query Example 1input item 1232245635 query 123456output 245566explanation for queries01 12 item price 1 hence answer query 2 for queries12 item consider 12 24 the maximum beauty 4 for queries23 queries34 item consider 12 32 24 35 the maximum beauty 5 for queries45 queries56 item consider hence answer maximum beauty item ie 6example 2input item 12121314 query 1output 4explanation the price item equal 1 choose item maximum beauty 4 note multiple item price andor beauty example 3input item 101000 query 5output 0explanationno item price equal 5 item chosenhence answer query 0 Constraints1 itemslength querieslength 105itemsilength 21 pricei beautyi queriesj 109
0array
you n task m worker each task strength requirement store 0indexed integer array task ith task require tasksi strength complete the strength worker store 0indexed integer array worker jth worker have workersj strength each worker assign single task strength great equal task strength requirement ie workersj tasksiadditionally pill magical pill increase worker strength strength you decide worker receive magical pill worker magical pillGiven 0indexed integer array task worker integer pill strength return maximum number task complete Example 1input task 321 worker 033 pill 1 strength 1output 3ExplanationWe assign magical pill task follow give magical pill worker 0 Assign worker 0 task 2 0 1 1 assign worker 1 task 1 3 2 Assign worker 2 task 0 3 3example 2input task 54 worker 000 pill 1 strength 5output 1explanationwe assign magical pill task follow give magical pill worker 0 Assign worker 0 task 0 0 5 5example 3input task 101530 worker 010101010 pill 3 strength 10output 2explanationwe assign magical pill task follow give magical pill worker 0 worker 1 Assign worker 0 task 0 0 10 10 Assign worker 1 task 1 10 10 15the pill give worker strong task Constraintsn taskslengthm workerslength1 n m 5 1040 pill m0 tasksi workersj strength 109
0array
there n people line queuing buy ticket 0th person line n 1th person lineYou give 0indexed integer array ticket length n number ticket ith person like buy ticketsieach person take exactly 1 second buy ticket a person buy 1 ticket time end line happen instantaneously order buy ticket if person ticket leave buy person leave lineReturn time take person position k 0indexed finish buy ticket example 1input ticket 232 k 2output 6explanation in pass line buy ticket line 1 2 1 in second pass line buy ticket line 0 1 0the person position 2 successfully buy 2 ticket take 3 3 6 secondsexample 2input ticket 5111 k 0output 8explanation in pass line buy ticket line 4 0 0 0 in 4 pass person position 0 buying ticketsthe person position 0 successfully buy 5 ticket take 4 1 1 1 1 8 second Constraintsn ticketslength1 n 1001 ticketsi 1000 k n
0array
a string originalText encode slanted transposition cipher string encodedtext help matrix having fix number row rowsoriginalText place topleft bottomright mannerthe blue cell fill follow red cell yellow cell reach end originalText the arrow indicate order cell fill all cell fill the number column choose rightmost column fill originaltextencodedtext form append character matrix rowwise fashionthe character blue cell append encodedText red cell finally yellow cell the arrow indicate order cell accessedfor example originalText cipher row 3 encode follow mannerthe blue arrow depict originalText place matrix red arrow denote order encodedtext form in example encodedtext ch ie prgiven encode string encodedtext number row row return original string originalTextNote originaltext trail space the test case generate possible originalText example 1input encodedText ch ie pr row 3output cipherExplanation this example describe problem descriptionExample 2input encodedText iveo eed l te olc row 4Output love leetcodeexplanation the figure denote matrix encode originalText the blue arrow find originaltext encodedtextexample 3input encodedtext code row 1output codingexplanation since 1 row originalText encodedText constraints0 encodedtextlength 106encodedtext consist lowercase english letter onlyencodedtext valid encode originaltext trail spaces1 row 1000the testcase generate possible originaltext
2string
you give integer n indicate number people network each person label 0 n 1you give 0indexed 2D integer array restriction restrictionsi xi yi mean person xi person yi friend directly indirectly peopleinitially friend you give list friend request 0indexe 2D integer array request requestsj uj vj friend request person uj person vja friend request successful uj vj friend each friend request process give order ie requestsj occur requestsj 1 successful request uj vj direct friend future friend requestsreturn boolean array result resultj true jth friend request successful false notnote if uj vj direct friend request successful Example 1input n 3 restriction 01 request 0221output truefalseexplanationrequest 0 person 0 person 2 friend direct friend request 1 person 2 person 1 friend person 0 person 1 indirect friend 120example 2input n 3 restriction 01 request 1202output truefalseexplanationrequest 0 person 1 person 2 friend direct friendsrequ 1 person 0 person 2 friend person 0 person 1 indirect friend 021example 3input n 5 restriction 011223 request 04123134output truefalsetruefalseexplanationrequest 0 person 0 person 4 friend direct friendsrequ 1 person 1 person 2 friend directly restrictedrequ 2 person 3 person 1 friend direct friendsrequ 3 person 3 person 4 friend person 0 person 1 indirect friend 0431 Constraints2 n 10000 restrictionslength 1000restrictionsilength 20 xi yi n 1xi yi1 requestslength 1000requestsjlength 20 uj vj n 1uj vj
1graph
there n house evenly line street house beautifully paint you give 0indexed integer array color length n colorsi represent color ith houseReturn maximum distance house different colorsThe distance ith jth house absi j absx absolute value x example 1input color 1116111output 3explanation in image color 1 blue color 6 redthe furth house different color house 0 house 3House 0 color 1 house 3 color 6 the distance abs0 3 3note house 3 6 produce optimal answerexample 2input color 18383output 4explanation in image color 1 blue color 8 yellow color 3 greenThe furth house different color house 0 house 4House 0 color 1 house 4 color 3 the distance abs0 4 4example 3input color 01output 1explanation the furth house different color house 0 house 1house 0 color 0 house 1 color 1 the distance abs0 1 1 Constraintsn colorslength2 n 1000 colorsi 100test datum generate house different color
0array
you want water n plant garden watering the plant arrange row label 0 n 1 leave right ith plant locate x There river x 1 refill watering atEach plant need specific water you water plant follow waywater plant order leave rightafter water current plant water completely water plant return river fully refill watering canyou refill watering earlyyou initially river ie x 1 it take step unit xaxisgiven 0indexe integer array plant n integer plantsi water ith plant need integer capacity represent watering capacity return number step need water plant Example 1input plant 2233 capacity 5output 14explanation Start river water Walk plant 0 1 step water watering 3 unit water Walk plant 1 1 step water Watering 1 unit water since completely water plant 2 walk river refill 2 step Walk plant 2 3 step water watering 2 unit water since completely water plant 3 walk river refill 3 step Walk plant 3 4 step water itSteps need 1 1 2 3 3 4 14example 2input plant 111423 capacity 4Output 30explanation Start river water Water plant 0 1 2 3 step return river 3 step water plant 3 4 step return river 4 step water plant 4 5 step return river 5 step water plant 5 6 stepsstep need 3 3 4 4 5 5 6 30example 3input plant 7777777 capacity 8Output 49explanation you refill water plantstep need 1 1 2 2 3 3 4 4 5 5 6 6 7 49 Constraintsn plantslength1 n 10001 plantsi 106maxplantsi capacity 109
0array
design datum structure find frequency give value give subarrayThe frequency value subarray number occurrence value subarrayimplement RangeFreqQuery classRangeFreqQueryint arr Constructs instance class give 0indexed integer array arrint queryint leave int right int value return frequency value subarray arrleftrighta subarray contiguous sequence element array arrleftright denote subarray contain element num index leave right inclusive Example 1inputrangefreqquery query query12 33 4 56 22 2 34 33 22 12 34 56 1 2 4 0 11 33outputnull 1 2explanationrangefreqquery rangefreqquery new RangeFreqQuery12 33 4 56 22 2 34 33 22 12 34 56rangefreqqueryquery1 2 4 return 1 the value 4 occur 1 time subarray 33 4rangefreqqueryquery0 11 33 return 2 the value 33 occur 2 time array Constraints1 arrlength 1051 arri value 1040 leave right arrlengthat 105 call query
0array
you give 0indexed string hamster hamstersi eitherH indicate hamster index indicate index emptyyou add number food bucket index order feed hamster a hamster fed food bucket leave right more formally hamster index fed place food bucket index 1 andor index 1return minimum number food bucket place index feed hamster 1 impossible feed example 1input hamster hhoutput 2explanation we place food bucket index 1 2it show place food bucket hamster fedexample 2input hamster hhoutput 1explanation we place food bucket index 2example 3Input hamster HHHOutput 1explanation if place food bucket index show hamster index 2 able eat Constraints1 hamsterslength 105hamstersi eitherH
2string
there m x n grid 0 0 topleft cell m 1 n 1 bottomright cell you give integer array startpos startpos startrow startcol indicate initially robot cell startrow startcol you give integer array homePos homepos homerow homecol indicate home cell homerow homecolthe robot need home it cell direction leave right outside boundary every incur cost you give 0indexed integer array rowcost length m colcost length nif robot move cell row r cost rowcostsrif robot move leave right cell column c cost colcostscreturn minimum total cost robot return home Example 1input startpos 1 0 homepos 2 3 rowcost 5 4 3 colcosts 8 2 6 7output 18explanation one optimal path thatstarte 1 0 it go 2 0 this cost rowcosts2 3 it go right 2 1 this cost colcosts1 2 it go right 2 2 this cost colcosts2 6 it go right 2 3 this cost colCosts3 7the total cost 3 2 6 7 18example 2input startpos 0 0 homepos 0 0 rowcost 5 colcosts 26output 0explanation the robot home since move occur total cost 0 constraintsm rowcostslengthn colCostslength1 m n 1050 rowcostsr colcostsc 104startposlength 2homeposlength 20 startrow homerow m0 startcol homecol n
0array
a farmer rectangular grid land m row n column divide unit cell each cell fertile represent 1 barren represent 0 all cell outside grid consider barrena pyramidal plot land define set cell follow criteriaThe number cell set great 1 cell fertileThe apex pyramid topmost cell pyramid the height pyramid number row cover let r c apex pyramid height h then plot comprise cell j r r h 1 c r j c run inverse pyramidal plot land define set cell similar criteriaThe number cell set great 1 cell fertileThe apex inverse pyramid bottommost cell inverse pyramid the height inverse pyramid number row cover let r c apex pyramid height h then plot comprise cell j r h 1 r c r j c r iSome example valid invalid pyramidal inverse pyramidal plot show black cell indicate fertile cellsGiven 0indexe m x n binary matrix grid represent farmland return total number pyramidal inverse pyramidal plot find grid Example 1input grid 01101111output 2explanation the 2 possible pyramidal plot show blue red respectivelythere inverse pyramidal plot grid hence total number pyramidal inverse pyramidal plot 2 0 2example 2input grid 111111output 2explanation the pyramidal plot show blue inverse pyramidal plot show red hence total number plot 1 1 2example 3input grid 11110111111111101001output 13explanation there 7 pyramidal plot 3 show 2nd 3rd figuresThere 6 inverse pyramidal plot 2 show figureThe total number plot 7 6 13 Constraintsm gridlengthn gridilength1 m n 10001 m n 105gridij 0 1
0array
you give 0indexed integer array nums target element targetA target index index numsi targetReturn list target index num sort num nondecrease order if target index return list the return list sort increase order Example 1input num 12523 target 2Output 12Explanation after sort num 12235the index numsi 2 1 2example 2input num 12523 target 3output 3explanation after sort num 12235the index numsi 3 3example 3input num 12523 target 5output 4explanation after sort num 12235the index numsi 5 4 constraints1 numslength 1001 numsi target 100
0array
you give 0indexed array num n integer integer kThe kradius average subarray nums center index radius k average element num indice k k inclusive if k elements index kradius average 1Build return array avgs length n avgsi kradius average subarray center index iThe average x element sum x element divide x integer division the integer division truncate zero mean lose fractional partfor example average element 2 3 1 5 2 3 1 5 4 11 4 275 truncate 2 example 1input num 743918526 k 3Output 111544111explanation avg0 avg1 avg2 1 k element index the sum subarray center index 3 radius 3 7 4 3 9 1 8 5 37 use integer division avg3 37 7 5 for subarray center index 4 avg4 4 3 9 1 8 5 2 7 4 for subarray center index 5 avg5 3 9 1 8 5 2 6 7 4 avg6 avg7 avg8 1 k element indexexample 2input num 100000 k 0output 100000explanation the sum subarray center index 0 radius 0 100000 avg0 100000 1 100000example 3input num 8 k 100000output 1explanation avg0 1 k element index 0 Constraintsn numslength1 n 1050 numsi k 105
0array
you give 0indexed array distinct integer numsthere element num low value element high value we minimum maximum respectively your goal remove element arrayA deletion define remove element array remove element arrayreturn minimum number deletion remove minimum maximum element array Example 1input num 210754186output 5explanation the minimum element array nums5 1the maximum element array nums1 10we remove minimum maximum remove 2 element 3 element backthis result 2 3 5 deletion minimum number possibleexample 2input num 041918235output 3explanation the minimum element array nums1 4the maximum element array nums2 19we remove minimum maximum remove 3 element frontthis result 3 deletion minimum number possibleexample 3input num 101output 1explanation there element array make minimum maximum elementwe remove 1 deletion Constraints1 numslength 105105 numsi 105the integer num distinct
0array
you give integer n indicate n people number 0 n 1 you give 0indexed 2D integer array meeting meetingsi xi yi timei indicate person xi person yi meet timei a person attend multiple meeting time finally give integ firstPersonPerson 0 secret initially share secret person firstPerson time 0 this secret share time meeting take place person secret more formally meet person xi secret timei share secret person yi vice versaThe secret share instantaneously that person receive secret share people meeting time framereturn list people secret meeting take place you return answer order Example 1input n 6 meeting 1252381510 firstPerson 1Output 01235explanationat time 0 person 0 share secret person 1at time 5 person 1 share secret person 2at time 8 person 2 share secret person 3at time 10 person 1 share secret person 5thus people 0 1 2 3 5 know secret meetingsexample 2input n 4 meeting 313122033 firstPerson 3Output 013explanationat time 0 person 0 share secret person 3at time 2 person 1 person 2 know secretAt time 3 person 3 share secret person 0 person 1Thus people 0 1 3 know secret meetingsexample 3input n 5 meeting 342121231 firstPerson 1output 01234explanationat time 0 person 0 share secret person 1at time 1 person 1 share secret person 2 person 2 share secret person 3note person 2 share secret time receive itat time 2 person 3 share secret person 4thus people 0 1 2 3 4 know secret meeting Constraints2 n 1051 meetingslength 105meetingsilength 30 xi yi n 1xi yi1 timei 1051 firstPerson n 1
1graph
you give integer array digit element digit the array contain duplicatesyou need find unique integer follow give requirementsthe integer consist concatenation element digit arbitrary orderthe integer lead zerosThe integer evenfor example give digit 1 2 3 integer 132 312 follow requirementsreturn sorted array unique integer Example 1input digit 2130output 102120130132210230302310312320explanation all possible integer follow requirement output array Notice odd integer integer lead zerosexample 2input digit 22882output 222228282288822828882explanation the digit time appear digit in example digit 8 twice time 288 828 882 example 3input digit 375output Explanation no integer form give digit Constraints3 digitslength 1000 digitsi 9
0array
you give 0indexed 2D integer array pair pairsi starti endi an arrangement pair valid index 1 pairslength endi1 startireturn valid arrangement pairsNote the input generate exist valid arrangement pair example 1input pair 514511994output 119944551explanationthis valid arrangement endi1 equal startiend0 9 9 start1 end1 4 4 start2end2 5 5 start3example 2input pair 133221output 133221explanationthis valid arrangement endi1 equal startiend0 3 3 start1end1 2 2 start2the arrangement 211332 322113 validExample 3input pair 121321output 122113explanationthis valid arrangement endi1 equal startiend0 2 2 start1end1 1 1 start2 Constraints1 pairslength 105pairsilength 20 starti endi 109starti endino pair exactly sameThere exist valid arrangement pair
1graph
you give integer array num integer k you want find subsequence num length k large sumreturn subsequence integer array length kA subsequence array derive array delete element change order remain element Example 1input num 2133 k 2output 33explanationthe subsequence large sum 3 3 6example 2input num 1234 k 3Output 134explanation the subsequence large sum 1 3 4 6example 3input num 3433 k 2output 34explanationthe subsequence large sum 3 4 7 another possible subsequence 4 3 constraints1 numslength 1000105 numsi 1051 k numslength
0array
you gang thief plan rob bank you give 0indexed integer array security securityi number guard duty ith day the day number start 0 you give integer timethe ith day good day rob bank ifthere time day ith dayThe number guard bank time day nonincrease andthe number guard bank time day nondecreasingMore formally mean day good day rob bank securityi time securityi time 1 securityi securityi time 1 securityi timereturn list day 0indexe good day rob bank the order day return matter Example 1input security 5333562 time 2output 23explanationon day 2 security0 security1 security2 security3 security4On day 3 security1 security2 security3 security4 security5No day satisfy condition day 2 3 good day rob bankExample 2input security 11111 time 0output 01234explanationsince time equal 0 day good day rob bank return dayexample 3input security 123456 time 2output ExplanationNo day 2 day nonincrease number guardsthus day good day rob bank return list Constraints1 securitylength 1050 securityi time 105
0array