{ }codelper
TODAYFri · 2026

Today's problem

Learn to Code, One Day at a Time.

two pointerscharacter codesP0155

Cutting the shortest piece from a necklace

There is a necklace of n beads strung in a circle. Each bead has one lowercase English letter on it, and the i-th character of the necklace string S is the i-th bead. Because the necklace is round, the 1st bead comes again after the n-th bead. You want to cut out some consecutive beads so that you have every letter of string T, at least as many times as it appears in T. The beads you cut out start at some bead and continue in the direction of increasing numbers (after the n-th comes the 1st), and the same bead cannot be used twice. Cut out as few beads as possible. If there are several ways, choose the one whose starting bead has the smallest number. Print the number of the starting bead and the number of beads cut out on one line, separated by a space. If no cut works, print -1.

Input
The first line has S and the second line has T.
Both consist of lowercase English letters only.
1 ≤ length n of S ≤ 100,000, 1 ≤ length of T ≤ 100,000
Output
The number of the starting bead and the number of beads on one line, separated by a space, or -1
Example 1 · stdin
cabbad
dc
stdout
6 2
Example 2 · stdin
ab
aa
stdout
-1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

Learn

From the basics to sorting and recursion, in the same order for every language — plus what only some languages have, like pointers and classes. Switch languages instantly on any lesson.

A

Basics

4 lessons
  1. 01Printing to the screenYour first line of code: print text and the result of a calculation.
  2. 02Variables and valuesGive a value a name so you can reuse and change it.
  3. 03Reading inputRead text and numbers from the keyboard (standard input).
  4. 04Arithmetic and divisionAdd, subtract and multiply work the same everywhere — division doesn't.
B

Control flow

4 lessons
  1. 05ConditionsDo different things depending on a condition: if · else if · else, plus switch.
  2. 06LoopsDo the same thing many times: for and while.
  3. 07More loopsTaking values one by one, going backwards, reading up to an end marker, and the run-at-least-once do-while.
  4. 08Booleans and the ternary operatorKeeping true/false in a variable, choosing one of two values, and asking "is it one of these?".
C

Data

5 lessons
  1. 09StringsLength, uppercase, reverse, and picking one character.
  2. 10Lists and arraysMany values in a row: count, first and last, sum, transform all.
  3. 11Working with single charactersOne character as a value: its code, letter arithmetic, the i-th character, repeating.
  4. 12Building stringsBuild a string from pieces, join with a separator, print values on one line.
  5. 13Editing listsContains, remove, reverse, swap, fill with one value, copy.
D

Functions

2 lessons
  1. 14FunctionsBundle work under a name, take values and return a result — plus recursion.
  2. 15More about functionsScope, returning several values, and passing functions as values.
E

Going further

10 lessons
  1. 16Dictionaries (maps)Find and update values by key: counting words, checking for a key, iterating in key order.
  2. 17SortingPut values in order: smallest first, largest first, or by a rule you choose.
  3. 182D lists (grids)Grids of rows and columns: reading them, row and column sums, and neighbours inside the bounds.
  4. 19Working with stringsSlicing, finding, replacing, trimming, comparing and padding.
  5. 20Integers and floating pointWhy 0.1 + 0.2 isn't 0.3, printing a fixed number of decimals, rounding rules and integer overflow.
  6. 21RecursionA function that calls itself: base cases, call-stack depth, loops and memoization.
  7. 22Common mistakes and error messagesHow to read error messages, and the mistakes every language shares: off-by-one, = vs ==, integer division, null, out-of-range indexes.
  8. 23Absolute value, powers, square rootsDropping the sign, multiplying many times, and finding the value whose square is a number.
  9. 24Counting, running totals, groupingIn one pass: count what matches, carry the value so far, and collect items by key.
  10. 25Lists of records and enumsCollect records in a list, and give names to a small fixed set of values.
F

Algorithms

8 lessons
  1. 26Simulation and Brute ForceDo exactly what the story says, step by step, and try every candidate without skipping one.
  2. 27Stacks and QueuesA stack hands back the newest item first; a queue hands back the oldest first.
  3. 28Binary SearchThrow away half of a sorted range at a time to find a value, or the first position that meets a condition.
  4. 29Prefix sums and two pointersGet the sum of any range with one subtraction, and find a range by moving two positions forward only.
  5. 30GCD, primes and number basesFind the GCD with remainders, sift out primes with a sieve, and write a number in another base.
  6. 31The greedy method and priority queuesTake what looks best at each step, and use a queue that hands out the smallest value right away.
  7. 32Graphs and depth-first searchWrite down who is connected to whom, then visit everything you can reach.
  8. 33Breadth-first search and topological sortSpread out from the nearest places with a queue to get the fewest steps, and line tasks up so prerequisites come first.
G

Language-specific

10 lessons
  1. 34PointersC++ · CCarry around where a value lives (its address) and change the caller's variable.
  2. 35Dynamic memoryC++ · CBorrow exactly as much memory as you need at run time, and always give it back.
  3. 36StructsC# · C++ · CBundle related values into one unit, and know whether that unit is copied or shared.
  4. 37Classes and objectsPython · JavaScript · TypeScript · Java · C# · C++Bundle data (fields) and behavior (methods) into one blueprint, then make many objects from it.
  5. 38Interfaces and genericsTypeScript · Java · C#An interface promises "these methods exist"; generics let one function work for many types.
  6. 39LINQ and streamsJava · C#Chain filtering, mapping, grouping and sorting into one pipeline instead of writing loops.
  7. 40Pythonic codePythonComprehensions, slicing with steps, unpacking, enumerate and zip, in, f-strings, and three traps.
  8. 41JavaScript equality and truthinessJavaScript · TypeScript== vs ===, falsy values, ?? vs ||, numbers that are all doubles, undefined vs null, and what TypeScript catches.
  9. 42C++ references and the STLC++& and const references, vector/map/set/unordered_map, algorithms that take lambdas, and the copy, invalidation and auto-insert traps.
  10. 43What makes Craykon differentCraykonKeywords in your own language, a null that stops calculations, a strict ==, and a switch that never falls through.

Problems

Every problem has reference solutions in every language it accepts (usually all 8; language-specific topics like pointers or classes take only those languages), machine-checked to produce identical answers.

  1. Copying a guestbook line8P0311
  2. Sum of two numbers8P0001
  3. Bonus-added scores joined with commas8P0373
  4. Marbles passed in turn8P0251
  5. The shorter one stands in front8P0344
  6. Four lines of true and false8P0217
  7. Ticket number from a seat code8P0226
  8. Sale price, or list price if there is none8P0281
  9. Distance per liter8P0216
  10. Sum of digits8P0006
  11. Grid distance8P0017
  12. A photo fitted to a square frame8P0254
  13. Letter grades8P0011
  14. Leap year8P0019
  15. Locker extra fee8P0372
  16. Three-day temperature trend8P0227
  17. Clap game8P0002
  18. Star triangle8P0007
  19. One row of the times table8P0022
  20. One more throw for yut or mo8P0255
  21. First multiple8P0023
  22. Street lamps, with one at the very end8P0371
  23. A reading marathon that grows every day8P0282
  24. Count the vowels8P0009
  25. First and last position of a character8P0053
  26. Letters picked along the diagonal8P0283
  27. Count the words8P0012
  28. Palindrome check8P0004
  29. Reverse it, keep the sign8P0252
  30. Swap the case8P0025
  31. Largest number and its position8P0005
  32. Numbers of the students who retake8P0374
  33. Showing one page of a board8P0284
  34. Sort the numbers8P0036
  35. Sorting sign letters8P0253
  36. Is it on the list?8P0059
  37. Swapping places in pairs8P0312
  38. Dart scores thrown in turns8P0342
  39. Mornings at or above average8P0343
  40. A thermometer that cannot leave its scale8P0402
  41. Balls that landed in the sandbox8P0285
  42. Numbering the lines of a song8P0347
  43. Score statistics8P0003
  44. Exactly the money you have8P0043
  45. Sum to the end8P0018
  46. Weight on the scale8P0221
  47. Swap the cards8P0046
  48. Big sum8P0015
  49. Truncate, floor, round8P0044
  50. A siren that keeps sounding until switched off8P0289
  51. Letter chain8P0045
  52. Ride capacity8P0086
  53. Three hops to the power box contact8P0286
  54. Grading addition homework8P0222
  55. Seconds to H:MM:SS8P0013
  56. Free-throw success rate sheet8P0314
  57. Weekday after k days8P0016
  58. Round half to even8P0048
  59. Powers that fit8P0050
  60. Closest to the target8P0218
  61. Where is the square root8P0049
  62. Member discount and delivery fee8P0191
  63. Kite-flying notice board8P0315
  64. Middle of three8P0020
  65. Four-operation calculator8P0021
  66. Password rule checker8P0098
  67. Fibonacci number8P0010
  68. Counting temperature records8P0219
  69. Count the digits8P0052
  70. Loading a delivery truck in order8P0223
  71. Count down by steps8P0024
  72. Running total until zero8P0051
  73. Characters left in a message with Korean text8P0341
  74. Letter numbers in a note8P0192
  75. Cut from the a-th to the b-th character8P0054
  76. Reverse the word order8P0028
  77. A note cipher that reverses each half8P0316
  78. Letter pyramid8P0097
  79. Caesar cipher8P0026
  80. Stamp a case pattern8P0230
  81. Find and replace all8P0055
  82. Count overlapping occurrences8P0030
  83. Compare two words in dictionary order8P0056
  84. Right-align the names8P0029
  85. Trim whitespace from each line8P0057
  86. Run-length compression8P0027
  87. Digit ribbon pieces8P0095
  88. Travel time on a one-way bus route8P0224
  89. Remove every match8P0058
  90. Rotate a list right8P0032
  91. Row and column sums8P0033
  92. Number order and dictionary order8P0320
  93. Masking banned words in chat8P0194
  94. Edit only the copy8P0060
  95. Stamping a grid8P0061
  96. Shortest to the front, tallest to the back8P0317
  97. Second largest8P0031
  98. Class averages and the year average8P0225
  99. Tally scans in order8P0220
  100. Phone book lookup8P0063
  101. Only the last vote counts8P0228
  102. Find mutual picks8P0256
  103. Find stock by part-code range8P0229
  104. Remove duplicates8P0035
  105. Booths that start when k students gather8P0349
  106. Prime check8P0008
  107. A box-count function with defaults8P0257
  108. Tidy locker numbers8P0196
  109. Pick the top word with a key function passed in8P0318
  110. A balance with unequal arms8P0345
  111. Fireflies sitting in a row8P0350
  112. Candies placed every k seats around a round table8P0313
  113. Count primes that stay prime reversed8P0258
  114. To binary8P0038
  115. The busiest stretch of the bus8P0259
  116. Merge the logs of two entrances8P0260
  117. The books the librarian pulled out8P0375
  118. Whose birthday comes next8P0376
  119. Fewest coins8P0041
  120. Ways to climb stairs8P0042
  121. The pile of lunch trays8P0348
  122. Umbrella stand: first come, first served8P0351
  123. Stove warmth spreading through a classroom8P0378
  124. The seeker's walk in hide-and-seek8P0377
  125. Following the crossroad notes8P0380
  126. Ranks fixed by the clues alone8P0381
  127. Cutting the longest rice cake first8P0379
  128. Café stamp cards6P0261
  129. A game character that reports its own status6P0346
  130. Weekend farm plot records8P0319
  131. Which way the turtle faces6P0077
  132. Coupons used in order5P0199
  133. Min, max and sum through pointers2P0073
  134. Walking to the longest run with pointers2P0074
  135. Keeping the words2P0075
  136. Name tags pointing at the same list8P0262
  137. The robot that bounces back3P0203
  138. Flip and filter a grid1P0083
  139. One recent list, used twice4P0204
  140. Second-hand market search box6P0263
  141. Checking lock records8P0287
  142. Neighbors of a new locker8P0288
  143. Shelf label check character8P0161
  144. Unfolding lines continued with a backslash8P0325
  145. Scale log that wraps anywhere8P0231
  146. Sales log totals8P0102
  147. Temperature strip chart8P0164
  148. Blocks and shadowed variables8P0087
  149. Dart scoreboard: values with different lifetimes8P0328
  150. Running a sorting network8P0133
  151. Does it end in binary?8P0359
  152. Permission bit checker8P0132
  153. Checking school trip forms8P0324
  154. Building a shuttle bus timetable8P0163
  155. Overage Charge on a Data Plan8P0387
  156. Fill blanks with the last value8P0047
  157. A counter whose wheels have different sizes8P0266
  158. Meeting time in cities around the world8P0166
  159. Scaling a recipe to the head count8P0232
  160. Part size tolerance check8P0134
  161. How far the delivery drone flew8P0233
  162. Streetlamps Along a Path8P0389
  163. Parcel rate table8P0167
  164. Parking fee calculator8P0136
  165. Transposing a melody by k semitones8P0401
  166. Admission by completed years of age8P0169
  167. Counting places for billboards on a tile wall8P0270
  168. Dice game: roll again on a 68P0264
  169. Table of shared free days8P0234
  170. Multi-month calendar8P0126
  171. Vending machine change8P0127
  172. A bank ledger with commas8P0173
  173. Progressive income tax8P0137
  174. Elevator log with no floor 08P0235
  175. The longest stretch typed with one hand8P0269
  176. Mark where two lines differ8P0143
  177. Normalize a web address path8P0144
  178. Wrap to a width8P0104
  179. Read the settings after the address8P0236
  180. Mirror lettering for a window8P0174
  181. A horizontal bar report8P0175
  182. Title case with exception words8P0145
  183. Template filler8P0101
  184. Find next and find previous8P0356
  185. Case-insensitive sort8P0103
  186. Guide Words on Dictionary Pages8P0386
  187. Score table8P0096
  188. Finish a link by attaching search filters8P0290
  189. A tournament where winning tires you8P0180
  190. A frog on stepping stones8P0193
  191. Edit a playlist8P0110
  192. Best window average8P0106
  193. Folding a paper strip8P0354
  194. What the recipes are missing8P0237
  195. Save slots for a list8P0107
  196. Spiral fill8P0128
  197. Vertical survey histogram8P0150
  198. A function that reverses ranges8P0062
  199. Who moved after the seat swaps8P0176
  200. Tidying ranges of a warehouse shelf8P0177
  201. The day with the widest swing8P0238
  202. Checking a receipt with subtotals8P0268
  203. Average to two decimals8P0014
  204. Word frequency ranking8P0034
  205. Warehouse reorder report8P0147
  206. Shop inventory8P0064
  207. Live top three8P0109
  208. Merging Photo Album Tags8P0388
  209. Roster by number8P0065
  210. Union, intersection, difference8P0099
  211. Tiles that flip when stepped on8P0352
  212. Group by first letter8P0066
  213. The abacus that needs the fewest beads8P0355
  214. A function that takes any number of judge scores8P0333
  215. Meeting room slot checker8P0149
  216. A child's share passes to the grandchildren8P0265
  217. Shaping a list by passing rule functions8P0239
  218. Fold left, fold right8P0329
  219. Narrowing down a PIN from worn keys8P0321
  220. GCD and LCM8P0037
  221. Add fractions and simplify8P0094
  222. Counting when three lighthouses flash together8P0322
  223. Split into two primes8P0068
  224. From base a to base b8P0093
  225. Labels without the avoided digits8P0358
  226. Fast range sums8P0039
  227. Two numbers summing to S in a sorted list8P0069
  228. When is the room free?8P0240
  229. Height between the markers8P0327
  230. Most meetings in one room8P0090
  231. A rhythm game where combos build up8P0267
  232. Balanced brackets8P0040
  233. Ticket line8P0071
  234. The museum whose doors lock one by one8P0291
  235. Line numbers in a folded reply thread8P0292
  236. The person with the most friends in common8P0293
  237. A semester plan that keeps prerequisites8P0197
  238. Rebuild only the stale files8P0326
  239. Lend the least-ridden bike first8P0294
  240. Bank account objects6P0078
  241. Shared ticket numbers6P0079
  242. A different salary for each kind of employee6P0157
  243. Score ranking8P0067
  244. League table6P0080
  245. Hourglasses that run together6P0323
  246. Order state machine6P0156
  247. Filter logs by level6P0357
  248. One max for everything3P0081
  249. Smart-home devices grouped by what they can do5P0383
  250. Detaching train cars with a pointer to a pointer2P0201
  251. An array that doubles2P0158
  252. Copied robots3P0076
  253. The all-or-nothing vending machine3P0382
  254. Flip the class roster1P0123
  255. Notebook and pen gift sets8P0353
  256. A pair ledger you can search from both sides4P0384
  257. Orders by city2P0082
  258. Sorting out the cells dug in a treasure hunt6P0385
  259. Loose or strict equality2P0084
  260. Four ways to be the same2P0124
  261. A stock ledger passed by reference1P0085
  262. Coupling trains at the yard4P0207
  263. Human-readable file sizes8P0135
  264. Filtering and grouping a server log8P0165
  265. Tidying a bike ride log8P0162
  266. Reading measurement rows mixed with commas and comments8P0392
  267. Summarising a bundle of letters8P0295
  268. Receipt printer format strings8P0241
  269. Printing a byte dump table8P0396
  270. What the progress bar left behind8P0271
  271. A banner printed with a digit font8P0404
  272. Used before a value was put in8P0360
  273. Calculator cells assigned all at once8P0272
  274. Compound interest table8P0131
  275. Moving a value into smaller types8P0397
  276. Broken Sensors and the Alarm8P0362
  277. Decoding control-character notation8P0300
  278. The date some days later or earlier8P0170
  279. Split by Stake and the Leftover Won8P0363
  280. Mean and standard deviation of sensor readings8P0168
  281. Sprinkler reach8P0129
  282. Trading robot: one action a day8P0330
  283. TV remote keys8P0242
  284. Checking product codes against a template8P0273
  285. Comparing products rule by rule8P0301
  286. Taking every few diagonal stripes of a patchwork8P0335
  287. Darts countdown game8P0140
  288. Slime Hunting Log8P0390
  289. Sort the digits and subtract, again and again8P0209
  290. Babylonian square root8P0130
  291. Retry with backoff8P0138
  292. A ruler made of characters8P0172
  293. Rewinding a work log to find the first row8P0331
  294. The next level keeps moving away8P0296
  295. Following an ATM's state8P0139
  296. A letter tape that turns and flips8P0297
  297. Imitating Python's a:b:c slicing8P0274
  298. Shortening long file names in the middle8P0395
  299. Split CSV with quotes8P0105
  300. Building a back-of-the-book index8P0302
  301. Reading a knitting row from the back8P0332
  302. Script rewrite in one pass8P0243
  303. Redact secrets in a log8P0171
  304. Natural sort of file names8P0142
  305. Markdown table of contents8P0141
  306. Trimming values in a config file8P0393
  307. Card row clean-up commands8P0244
  308. Copy, cut and paste8P0298
  309. Flipping through class-photo lineups8P0208
  310. Filtering chat spam by what is still on screen8P0391
  311. Theater seats and a waiting line8P0146
  312. Picking the restaurant that disappoints no one much8P0334
  313. Ranking stations by average temperature8P0195
  314. Budget ledger by category8P0178
  315. Runoff with ranked ballots8P0148
  316. A small library's loan ledger8P0179
  317. Laying Wires on an Endless Board8P0364
  318. Ordering a warehouse stock ledger by cell8P0394
  319. Anagram groups8P0108
  320. Grouping recipes with the same ratio8P0280
  321. Reading numbers in Korean8P0200
  322. A calculation tree that evaluates only the chosen side8P0275
  323. Binding Named Arguments8P0361
  324. Pieces nobody attacks8P0299
  325. Letter arrangements8P0100
  326. Reading duration notation8P0366
  327. Run twice: lexical and dynamic scope8P0245
  328. Cars at a traffic light8P0114
  329. An elevator with two buttons8P0181
  330. Building a gear train8P0185
  331. Count numbers with k prime factors8P0113
  332. Primes in a smudged ledger8P0182
  333. Fast rectangle sums on a grid8P0092
  334. Pairs within k8P0112
  335. Cutting the shortest piece from a necklace8P0155
  336. Cut ribbons evenly8P0070
  337. Backup disk size8P0111
  338. Transfers on a timetable where expresses overtake8P0304
  339. Ways to make an amount with coins8P0088
  340. Longest increasing subsequence8P0089
  341. Packing a knapsack8P0116
  342. Longest common subsequence8P0117
  343. The cheapest way to fix a caption8P0153
  344. First greater number to the right8P0091
  345. A notepad with undo and redo8P0187
  346. Round-robin CPU8P0115
  347. The order of moves to measure with two jugs8P0210
  348. Exploring a cave by feel, picking up keys8P0190
  349. Friend groups8P0118
  350. Slack time of festival tasks8P0303
  351. Editing a floor plan with chained methods6P0276
  352. Parcel trucks that leave when full8P0247
  353. Hands of five dice6P0198
  354. Task queue and median3P0121
  355. A box ranking built from an array of pointers2P0246
  356. A table whose rows have different lengths2P0202
  357. A Tiny Heap Manager8P0365
  358. Fix by reference, find with lower_bound1P0125
  359. Cloned adventurers and a shared vault3P0159
  360. Build an answer-sheet score table1P0206
  361. Top k per stage2P0122
  362. Matching the product table and the order table2P0160
  363. Identical parcels and parcels with the same contents8P0205
  364. Drawing a folder tree8P0248
  365. Finding names in nested blocks8P0183
  366. Round table seating rules8P0184
  367. Tile wall and corner numbers8P0399
  368. An elevator that turns when there is no more work8P0250
  369. Cutting grid paper into squares with nothing left8P0367
  370. Longest piece of three ribbon colors8P0398
  371. Numbers that split into small primes only8P0340
  372. Repeating fractions in another base8P0403
  373. Campfires that cool with distance and the warmth of the campsite8P0307
  374. Serving a round table8P0369
  375. A ridge walk that takes the cable car over the hardest section8P0306
  376. Choosing days to dry persimmons8P0368
  377. Stretching every streetlight equally8P0213
  378. A delayed line and the k-th train8P0370
  379. Sorting a table by column keys given in the input8P0308
  380. Choosing 3D printer orders that meet their deadlines8P0152
  381. The night watch that needs k people in every slot8P0310
  382. Ways the water can flow8P0154
  383. How many snacks to stock in the fridge8P0214
  384. Numbers that light S bars8P0279
  385. Taking marbles without copying8P0339
  386. A remainder calculator where adding comes first8P0186
  387. A ledger rolled back to named savepoints8P0305
  388. Counting two neighboring colors in a grouped bead design8P0400
  389. The kiln line where cracked pots cool and queue again8P0309
  390. A shortcut through up to K walls8P0119
  391. Paint drops where the most neighbors win8P0188
  392. Doors that flip every time you step8P0249
  393. Bridges that open only on odd or even minutes8P0336
  394. Island map8P0072
  395. A package installer that matches version ranges8P0189
  396. Breakers that trip from the bottom up8P0337
  397. A drone that swaps batteries8P0151
  398. Pipes that cut off water on their own8P0212
  399. A group chat you leave when the people you watch are gone8P0278
  400. Ordering tasks8P0120
  401. A sheet whose cells may call each other8P0215
  402. Removing packages nobody needs any more8P0338
  403. A bakery that sells the earliest expiry first8P0211
  404. A treatment order that grows more urgent with waiting8P0277

All problems →