Dataset Viewer
Auto-converted to Parquet
task_id
stringlengths
7
9
prompt
stringlengths
237
6.2k
entry_point
stringlengths
2
37
test
stringlengths
70
6.28k
given_tests
sequencelengths
1
6
canonical_solution
stringclasses
1 value
difficulty
stringclasses
3 values
added_tests
sequencelengths
0
0
APPS/2590
def max_of_min_2d_array(n: int, m: int, array: List[List[int]]) -> int: """ =====Function Descriptions===== min The tool min returns the minimum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.min(my_array, axis = 0) #Output : [1 0] print numpy.min(my_array, axis = 1) #Output : [2 3 1 0] print numpy.min(my_array, axis = None) #Output : 0 print numpy.min(my_array) #Output : 0 By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array. max The tool max returns the maximum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.max(my_array, axis = 0) #Output : [4 7] print numpy.max(my_array, axis = 1) #Output : [5 7 3 4] print numpy.max(my_array, axis = None) #Output : 7 print numpy.max(my_array) #Output : 7 By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array. =====Problem Statement===== You are given a 2-D array with dimensions NXM. Your task is to perform the min function over axis 1 and then find the max of that. =====Input Format===== The first line of input contains the space separated values of N and M. The next N lines contains M space separated integers. =====Output Format===== Compute the min along axis 1 and then print the max of that result. """ import numpy as np np_array = np.array(array) min_values = np.min(np_array, axis=1) return np.max(min_values)
max_of_min_2d_array
def check(candidate): assert candidate(4, 2, [[2, 5], [3, 7], [1, 3], [4, 0]]) == 3 check(max_of_min_2d_array)
[ "assert max_of_min_2d_array(4, 2, [[2, 5], [3, 7], [1, 3], [4, 0]]) == 3" ]
introductory
[]
APPS/3239
def guess_hat_color(a: str, b: str, c: str, d: str) -> int: """ # Task Four men, `a, b, c and d` are standing in a line, one behind another. There's a wall between the first three people (a, b and c) and the last one (d). a, b and c are lined up in order of height, so that person a can see the backs of b and c, person b can see the back of c, and c can see just the wall. There are 4 hats, 2 black and 2 white. Each person is given a hat. None of them can see their own hat, but person a can see the hats of b and c, while person b can see the hat of person c. Neither c nor d can see any hats. Once a person figures out their hat's color, they shouts it. ![](http://stuffbox.in/wp-content/uploads/2016/08/Guess-hat-colour-604x270.png) Your task is to return the person who will guess their hat first. You can assume that they will speak only when they reach a correct conclusion. # Input/Output - `[input]` string `a` a's hat color ("white" or "black"). - `[input]` string `b` b's hat color ("white" or "black"). - `[input]` string `c` c's hat color ("white" or "black"). - `[input]` string `d` d's hat color ("white" or "black"). - `[output]` an integer The person to guess his hat's color first, `1 for a, 2 for b, 3 for c and 4 for d`. """
guess_hat_color
def check(candidate): assert candidate('white', 'black', 'white', 'black') == 2 assert candidate('white', 'black', 'black', 'white') == 1 check(guess_hat_color)
[ "assert guess_hat_color('white', 'black', 'white', 'black') == 2" ]
introductory
[]
APPS/2468
def tictactoe(moves: List[List[int]]) -> str: """ Tic-tac-toe is played by two players A and B on a 3 x 3 grid. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares (" "). The first player A always places "X" characters, while the second player B always places "O" characters. "X" and "O" characters are always placed into empty squares, never on filled ones. The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play. Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending". You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first. Example 1: Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]] Output: "A" Explanation: "A" wins, he always plays first. "X " "X " "X " "X " "X " " " -> " " -> " X " -> " X " -> " X " " " "O " "O " "OO " "OOX" Example 2: Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]] Output: "B" Explanation: "B" wins. "X " "X " "XX " "XXO" "XXO" "XXO" " " -> " O " -> " O " -> " O " -> "XO " -> "XO " " " " " " " " " " " "O " Example 3: Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]] Output: "Draw" Explanation: The game ends in a draw since there are no moves to make. "XXO" "OOX" "XOX" Example 4: Input: moves = [[0,0],[1,1]] Output: "Pending" Explanation: The game has not finished yet. "X " " O " " " Constraints: 1 <= moves.length <= 9 moves[i].length == 2 0 <= moves[i][j] <= 2 There are no repeated elements on moves. moves follow the rules of tic tac toe. """
tictactoe
def check(candidate): assert candidate([[0, 0], [2, 0], [1, 1], [2, 1], [2, 2]]) == 'A' assert candidate([[0, 0], [1, 1], [0, 1], [0, 2], [1, 0], [2, 0]]) == 'B' assert candidate([[0, 0], [1, 1], [2, 0], [1, 0], [1, 2], [2, 1], [0, 1], [0, 2], [2, 2]]) == 'Draw' assert candidate([[0, 0], [1, 1]]) == 'Pending' check(tictactoe)
[ "assert tictactoe([[0, 0], [2, 0], [1, 1], [2, 1], [2, 2]]) == 'A'", "assert tictactoe([[0, 0], [1, 1], [0, 1], [0, 2], [1, 0], [2, 0]]) == 'B'", "assert tictactoe([[0, 0], [1, 1], [2, 0], [1, 0], [1, 2], [2, 1], [0, 1], [0, 2], [2, 2]]) == 'Draw'", "assert tictactoe([[0, 0], [1, 1]]) == 'Pending'" ]
introductory
[]
APPS/3231
def case_unification(s: str) -> str: """ # Task Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case. # Input/Output `[input]` string `s` String of odd length consisting of English letters. 3 ≤ inputString.length ≤ 99. `[output]` a string The resulting string. # Example For `s = "Aba"`, the output should be `"aba"` For `s = "ABa"`, the output should be `"ABA"` """
case_unification
def check(candidate): assert candidate('asdERvT') == 'asdervt' assert candidate('oyTYbWQ') == 'OYTYBWQ' assert candidate('bbiIRvbcW') == 'bbiirvbcw' assert candidate('rWTmvcoRWEWQQWR') == 'RWTMVCORWEWQQWR' check(case_unification)
[ "assert case_unification('Aba') == 'aba'", "assert case_unification('ABa') == 'ABA'" ]
introductory
[]
APPS/2961
def complete_series(a: List[int]) -> List[int]: """ You are given an array of non-negative integers, your task is to complete the series from 0 to the highest number in the array. If the numbers in the sequence provided are not in order you should order them, but if a value repeats, then you must return a sequence with only one item, and the value of that item must be 0. like this: ``` inputs outputs [2,1] -> [0,1,2] [1,4,4,6] -> [0] ``` Notes: all numbers are positive integers. This is set of example outputs based on the input sequence. ``` inputs outputs [0,1] -> [0,1] [1,4,6] -> [0,1,2,3,4,5,6] [3,4,5] -> [0,1,2,3,4,5] [0,1,0] -> [0] ``` """
complete_series
def check(candidate): assert candidate([0, 1]) == [0, 1] assert candidate([1, 4, 6]) == [0, 1, 2, 3, 4, 5, 6] assert candidate([3, 4, 5]) == [0, 1, 2, 3, 4, 5] assert candidate([2, 1]) == [0, 1, 2] assert candidate([1, 4, 4, 6]) == [0] check(complete_series)
[ "assert complete_series([0, 1]) == [0, 1]", "assert complete_series([1, 4, 6]) == [0, 1, 2, 3, 4, 5, 6]", "assert complete_series([3, 4, 5]) == [0, 1, 2, 3, 4, 5]", "assert complete_series([0, 1, 0]) == [0]", "assert complete_series([2, 1]) == [0, 1, 2]", "assert complete_series([1, 4, 4, 6]) == [0]" ]
introductory
[]
APPS/3813
def does_fred_need_houseboat(x: int, y: int) -> int: """ # Task Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the rest of his life, he needs to know if his land is going to be lost to erosion. After doing more research, Fred has learned that the land that is being lost forms a semicircle. This semicircle is part of a circle centered at (0,0), with the line that bisects the circle being the `x` axis. Locations below the `x` axis are in the water. The semicircle has an area of 0 at the beginning of year 1. (Semicircle illustrated in the Figure.) ![](http://media.openjudge.cn/images/1005/semicircle.GIF) Given two coordinates `x` and `y`, your task is to calculate that Fred Mapper's house will begin eroding in how many years. Note: 1. No property will appear exactly on the semicircle boundary: it will either be inside or outside. 2. All locations are given in miles. 3. (0,0) will not be given. # Example For `x = 1, y = 1`, the result should be `1`. After 1 year, Fred Mapper's house will begin eroding. For `x = 25, y = 0`, the result should be `20`. After 20 year, Fred Mapper's house will begin eroding. # Input/Output - `[input]` integer `x` The X coordinates of the land Fred is considering. It will be an integer point numbers measured in miles. `-100 <= x <= 100` - `[input]` integer `y` The Y coordinates of the land Fred is considering. It will be an integer point numbers measured in miles. `0 <= y <= 100` - `[output]` an integer The first year (start from 1) this point will be within the semicircle AT THE END OF YEAR. """
does_fred_need_houseboat
def check(candidate): assert candidate(1, 1) == 1 assert candidate(25, 0) == 20 check(does_fred_need_houseboat)
[ "assert does_fred_need_houseboat(1, 1) == 1", "assert does_fred_need_houseboat(25, 0) == 20" ]
introductory
[]
APPS/3513
def folding(a: int, b: int) -> int: """ # Task John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part. After moving the square piece of paper aside, John wanted to make even more squares! He took the remaining (`a-b`) × `b` strip of paper and went on with the process until he was left with a square piece of paper. Your task is to determine how many square pieces of paper John can make. # Example: For: `a = 2, b = 1`, the output should be `2`. Given `a = 2` and `b = 1`, John can fold a `1 × 1` then another `1 × 1`. So the answer is `2`. For: `a = 10, b = 7`, the output should be `6`. We are given `a = 10` and `b = 7`. The following is the order of squares John folds: `7 × 7, 3 × 3, 3 × 3, 1 × 1, 1 × 1, and 1 × 1`. Here are pictures for the example cases. # Input/Output - `[input]` integer `a` `2 ≤ a ≤ 1000` - `[input]` integer `b` `1 ≤ b < a ≤ 1000` - `[output]` an integer The maximum number of squares. """
folding
def check(candidate): assert candidate(2, 1) == 2 assert candidate(10, 7) == 6 assert candidate(3, 1) == 3 assert candidate(4, 1) == 4 assert candidate(3, 2) == 3 assert candidate(4, 2) == 2 assert candidate(1000, 700) == 6 assert candidate(1000, 999) == 1000 check(folding)
[ "assert folding(2, 1) == 2", "assert folding(10, 7) == 6" ]
introductory
[]
APPS/4035
def substring_test(first: str, second: str) -> bool: """ Given 2 strings, your job is to find out if there is a substring that appears in both strings. You will return true if you find a substring that appears in both strings, or false if you do not. We only care about substrings that are longer than one letter long. #Examples: ```` *Example 1* SubstringTest("Something","Fun"); //Returns false *Example 2* SubstringTest("Something","Home"); //Returns true ```` In the above example, example 2 returns true because both of the inputs contain the substring "me". (so**ME**thing and ho**ME**) In example 1, the method will return false because something and fun contain no common substrings. (We do not count the 'n' as a substring in this Kata because it is only 1 character long) #Rules: Lowercase and uppercase letters are the same. So 'A' == 'a'. We only count substrings that are > 1 in length. #Input: Two strings with both lower and upper cases. #Output: A boolean value determining if there is a common substring between the two inputs. """
substring_test
def check(candidate): assert candidate('Something', 'Home') == True assert candidate('Something', 'Fun') == False assert candidate('Something', '') == False assert candidate('', 'Something') == False assert candidate('BANANA', 'banana') == True assert candidate('test', 'lllt') == False assert candidate('', '') == False assert candidate('1234567', '541265') == True assert candidate('supercalifragilisticexpialidocious', 'SoundOfItIsAtrocious') == True assert candidate('LoremipsumdolorsitametconsecteturadipiscingelitAeneannonaliquetligulautplaceratorciSuspendissepotentiMorbivolutpatauctoripsumegetaliquamPhasellusidmagnaelitNullamerostellustemporquismolestieaornarevitaediamNullaaliquamrisusnonviverrasagittisInlaoreetultricespretiumVestibulumegetnullatinciduntsempersemacrutrumfelisPraesentpurusarcutempusnecvariusidultricesaduiPellentesqueultriciesjustolobortisrhoncusdignissimNuncviverraconsequatblanditUtbibendumatlacusactristiqueAliquamimperdietnuncsempertortorefficiturviverra', 'thisisalongstringtest') == True assert candidate('Codewars is sweet!', 'is') == True check(substring_test)
[ "assert substring_test('Something', 'Fun') == False", "assert substring_test('Something', 'Home') == True" ]
introductory
[]
APPS/2905
def nickname_generator(name: str) -> str: """ Nickname Generator Write a function, `nicknameGenerator` that takes a string name as an argument and returns the first 3 or 4 letters as a nickname. If the 3rd letter is a consonant, return the first 3 letters. If the 3rd letter is a vowel, return the first 4 letters. If the string is less than 4 characters, return "Error: Name too short". **Notes:** - Vowels are "aeiou", so discount the letter "y". - Input will always be a string. - Input will always have the first letter capitalised and the rest lowercase (e.g. Sam). - The input can be modified """
nickname_generator
def check(candidate): assert candidate('Jimmy') == 'Jim' assert candidate('Samantha') == 'Sam' assert candidate('Sam') == 'Error: Name too short' assert candidate('Kayne') == 'Kay' assert candidate('Melissa') == 'Mel' assert candidate('James') == 'Jam' assert candidate('Gregory') == 'Greg' assert candidate('Jeannie') == 'Jean' assert candidate('Kimberly') == 'Kim' assert candidate('Timothy') == 'Tim' assert candidate('Dani') == 'Dan' assert candidate('Saamy') == 'Saam' assert candidate('Saemy') == 'Saem' assert candidate('Saimy') == 'Saim' assert candidate('Saomy') == 'Saom' assert candidate('Saumy') == 'Saum' assert candidate('Boyna') == 'Boy' assert candidate('Kiyna') == 'Kiy' assert candidate('Sayma') == 'Say' assert candidate('Ni') == 'Error: Name too short' assert candidate('Jam') == 'Error: Name too short' assert candidate('Suv') == 'Error: Name too short' check(nickname_generator)
[ "assert nickname_generator('Robert') == 'Rob'", "assert nickname_generator('Jeannie') == 'Jean'" ]
introductory
[]
APPS/4907
def candles(candlesNumber: int, makeNew: int) -> int: """ # Task When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? # Example For candlesNumber = 5 and makeNew = 2, the output should be `9`. Here is what you can do to burn 9 candles: ``` burn 5 candles, obtain 5 leftovers; create 2 more candles, using 4 leftovers (1 leftover remains); burn 2 candles, end up with 3 leftovers; create another candle using 2 leftovers (1 leftover remains); burn the created candle, which gives another leftover (2 leftovers in total); create a candle from the remaining leftovers; burn the last candle. Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. ``` # Input/Output - `[input]` integer `candlesNumber` The number of candles you have in your possession. Constraints: 1 ≤ candlesNumber ≤ 50. - `[input]` integer `makeNew` The number of leftovers that you can use up to create a new candle. Constraints: 2 ≤ makeNew ≤ 5. - `[output]` an integer """
candles
def check(candidate): assert candidate(5, 2) == 9 check(candles)
[ "assert candles(5, 2) == 9" ]
introductory
[]
APPS/3776
def segment_cover(A: List[int], L: int) -> int: """ # Task Given some points(array `A`) on the same line, determine the minimum number of line segments with length `L` needed to cover all of the given points. A point is covered if it is located inside some segment or on its bounds. # Example For `A = [1, 3, 4, 5, 8]` and `L = 3`, the output should be `2`. Check out the image below for better understanding: ![](https://codefightsuserpics.s3.amazonaws.com/tasks/segmentCover/img/example.png?_tm=1474900035857) For `A = [1, 5, 2, 4, 3]` and `L = 1`, the output should be `3`. segment1: `1-2`(covered points 1,2), segment2: `3-4`(covered points 3,4), segment3: `5-6`(covered point 5) For `A = [1, 10, 100, 1000]` and `L = 1`, the output should be `4`. segment1: `1-2`(covered point 1), segment2: `10-11`(covered point 10), segment3: `100-101`(covered point 100), segment4: `1000-1001`(covered point 1000) # Input/Output - `[input]` integer array A Array of point coordinates on the line (all points are different). Constraints: `1 ≤ A.length ≤ 50,` `-5000 ≤ A[i] ≤ 5000.` - `[input]` integer `L` Segment length, a positive integer. Constraints: `1 ≤ L ≤ 100.` - `[output]` an integer The minimum number of line segments that can cover all of the given points. """
segment_cover
def check(candidate): assert candidate([1, 3, 4, 5, 8], 3) == 2 assert candidate([-7, -2, 0, -1, -6, 7, 3, 4], 4) == 3 assert candidate([1, 5, 2, 4, 3], 1) == 3 assert candidate([1, 10, 100, 1000], 1) == 4 check(segment_cover)
[ "assert segment_cover([1, 3, 4, 5, 8], 3) == 2" ]
introductory
[]
APPS/2718
def timed_reading(max_length: int, text: str) -> int: """ # Task Timed Reading is an educational tool used in many schools to improve and advance reading skills. A young elementary student has just finished his very first timed reading exercise. Unfortunately he's not a very good reader yet, so whenever he encountered a word longer than maxLength, he simply skipped it and read on. Help the teacher figure out how many words the boy has read by calculating the number of words in the text he has read, no longer than maxLength. Formally, a word is a substring consisting of English letters, such that characters to the left of the leftmost letter and to the right of the rightmost letter are not letters. # Example For `maxLength = 4` and `text = "The Fox asked the stork, 'How is the soup?'"`, the output should be `7` The boy has read the following words: `"The", "Fox", "the", "How", "is", "the", "soup".` # Input/Output - `[input]` integer `maxLength` A positive integer, the maximum length of the word the boy can read. Constraints: `1 ≤ maxLength ≤ 10.` - `[input]` string `text` A non-empty string of English letters and punctuation marks. - `[output]` an integer The number of words the boy has read. """
timed_reading
def check(candidate): assert candidate(4, 'The Fox asked the stork, How is the soup?') == 7 assert candidate(1, '...') == 0 assert candidate(3, 'This play was good for us.') == 3 assert candidate(3, 'Suddenly he stopped, and glanced up at the houses') == 5 assert candidate(6, 'Zebras evolved among the Old World horses within the last four million years.') == 11 assert candidate(5, 'Although zebra species may have overlapping ranges, they do not interbreed.') == 6 assert candidate(1, 'Oh!') == 0 assert candidate(5, 'Now and then, however, he is horribly thoughtless, and seems to take a real delight in giving me pain.') == 14 check(timed_reading)
[ "assert timed_reading(4, 'The Fox asked the stork, How is the soup?') == 7" ]
introductory
[]
APPS/3351
def evil_code_medal(user_time: str, gold: str, silver: str, bronze: str) -> str: """ # Task `EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task. To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. You can be awarded `"Gold", "Silver" or "Bronze"` medal, or `"None"` medal at all. Only one medal (the best achieved) is awarded. You are given the time achieved for the task and the time corresponding to each medal. Your task is to return the awarded medal. Each time is given in the format `HH:MM:SS`. # Input/Output `[input]` string `userTime` The time the user achieved. `[input]` string `gold` The time corresponding to the gold medal. `[input]` string `silver` The time corresponding to the silver medal. `[input]` string `bronze` The time corresponding to the bronze medal. It is guaranteed that `gold < silver < bronze`. `[output]` a string The medal awarded, one of for options: `"Gold", "Silver", "Bronze" or "None"`. # Example For ``` userTime = "00:30:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"Silver"` For ``` userTime = "01:15:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"None"` # For Haskell version ``` In Haskell, the result is a Maybe, returning Just String indicating the medal if they won or Nothing if they don't. ``` """
evil_code_medal
def check(candidate): assert candidate("00:30:00", "00:15:00", "00:45:00", "01:15:00") == "Silver" assert candidate("01:15:00", "00:15:00", "00:45:00", "01:15:00") == "None" assert candidate("00:00:01", "00:00:10", "00:01:40", "01:00:00") == "Gold" assert candidate("00:10:01", "00:00:10", "00:01:40", "01:00:00") == "Bronze" assert candidate("00:00:01", "00:00:02", "00:00:03", "00:00:04") == "Gold" assert candidate("90:00:01", "60:00:02", "70:00:03", "80:00:04") == "None" assert candidate("03:15:00", "03:15:00", "03:15:01", "03:15:02") == "Silver" assert candidate("99:59:58", "99:59:57", "99:59:58", "99:59:59") == "Bronze" assert candidate("14:49:03", "77:39:08", "92:11:36", "94:07:41") == "Gold" assert candidate("61:01:40", "64:19:53", "79:30:02", "95:24:48") == "Gold" check(evil_code_medal)
[ "assert evil_code_medal(\"00:30:00\", \"00:15:00\", \"00:45:00\", \"01:15:00\") == \"Silver\"" ]
introductory
[]
APPS/4630
def decrypt(s: str) -> str: """ # Task Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information. For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tried encryption algorithms very complex, but the decryption process is tedious, especially when he needed to dial a speed dial. He eventually found the algorithm following: instead of writing the number itself, Ahmed multiplied by 10, then adds the result to the original number. For example, if the phone number is `123`, after the transformation, it becomes `1353`. Ahmed truncates the result (from the left), so it has as many digits as the original phone number. In this example Ahmed wrote `353` instead of `123` in his smart phone. Ahmed needs a program to recover the original phone number from number stored on his phone. The program return "impossible" if the initial number can not be calculated. Note: There is no left leading zero in either the input or the output; Input `s` is given by string format, because it may be very huge ;-) # Example For `s="353"`, the result should be `"123"` ``` 1230 + 123 ....... = 1353 truncates the result to 3 digit -->"353" So the initial number is "123" ``` For `s="123456"`, the result should be `"738496"` ``` 7384960 + 738496 ......... = 8123456 truncates the result to 6 digit -->"123456" So the initial number is "738496" ``` For `s="4334"`, the result should be `"impossible"` Because no such a number can be encrypted to `"4334"`. # Input/Output - `[input]` string `s` string presentation of n with `1 <= n <= 10^100` - `[output]` a string The original phone number before encryption, or `"impossible"` if the initial number can not be calculated. """
decrypt
def check(candidate): assert candidate('353') == '123' assert candidate('444') == '404' assert candidate('123456') == '738496' assert candidate('147') == '377' assert candidate('4334') == 'impossible' check(decrypt)
[ "assert decrypt('353') == '123'", "assert decrypt('123456') == '738496'", "assert decrypt('4334') == 'impossible'" ]
introductory
[]
APPS/2521
def reformat(s: str) -> str: """ Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. Example 1: Input: s = "a0b1c2" Output: "0a1b2c" Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations. Example 2: Input: s = "leetcode" Output: "" Explanation: "leetcode" has only characters so we cannot separate them by digits. Example 3: Input: s = "1229857369" Output: "" Explanation: "1229857369" has only digits so we cannot separate them by characters. Example 4: Input: s = "covid2019" Output: "c2o0v1i9d" Example 5: Input: s = "ab123" Output: "1a2b3" Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and/or digits. """
reformat
def check(candidate): assert candidate('a0b1c2') == '0a1b2c' or candidate('a0b1c2') == 'a0b1c2' or candidate('a0b1c2') == '0c2a1b' assert candidate('leetcode') == '' assert candidate('1229857369') == '' assert candidate('covid2019') == 'c2o0v1i9d' or candidate('covid2019') == '2c0o1v9i' assert candidate('ab123') == '1a2b3' or candidate('ab123') == 'a1b2c' check(reformat)
[ "assert reformat('a0b1c2') == '0a1b2c' or reformat('a0b1c2') == 'a0b1c2' or reformat('a0b1c2') == '0c2a1b'" ]
introductory
[]
APPS/2706
def pass_the_bill(total: int, conservative: int, reformist: int) -> int: """ # Story&Task There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants. You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it. In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no . However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not. Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed . In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`. # Input/Output - `[input]` integer `totalMembers` The total number of members. - `[input]` integer `conservativePartyMembers` The number of members in the Conservative Party. - `[input]` integer `reformistPartyMembers` The number of members in the Reformist Party. - `[output]` an integer The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway. # Example For `n = 8, m = 3 and k = 3`, the output should be `2`. It means: ``` Conservative Party member --> 3 Reformist Party member --> 3 the independent members --> 8 - 3 - 3 = 2 If 2 independent members change their minds 3 + 2 > 3 the bill will be passed. If 1 independent members change their minds perhaps the bill will be failed (If the other independent members is against the bill). 3 + 1 <= 3 + 1 ``` For `n = 13, m = 4 and k = 7`, the output should be `-1`. ``` Even if all 2 independent members support the bill there are still not enough votes to pass the bill 4 + 2 < 7 So the output is -1 ``` """
pass_the_bill
def check(candidate): assert candidate(8, 3, 3) == 2 assert candidate(13, 4, 7) == -1 assert candidate(7, 4, 3) == 0 assert candidate(11, 4, 1) == 2 assert candidate(11, 5, 1) == 1 assert candidate(11, 6, 1) == 0 assert candidate(11, 4, 4) == 2 assert candidate(11, 5, 4) == 1 assert candidate(11, 5, 5) == 1 assert candidate(11, 4, 6) == -1 assert candidate(11, 4, 5) == 2 assert candidate(15, 9, 3) == 0 assert candidate(16, 7, 8) == -1 assert candidate(16, 8, 7) == 1 assert candidate(16, 1, 8) == -1 check(pass_the_bill)
[ "assert pass_the_bill(8, 3, 3) == 2", "assert pass_the_bill(13, 4, 7) == -1" ]
introductory
[]
APPS/4536
def capitals_first(string: str) -> str: """ Create a function that takes an input String and returns a String, where all the uppercase words of the input String are in front and all the lowercase words at the end. The order of the uppercase and lowercase words should be the order in which they occur. If a word starts with a number or special character, skip the word and leave it out of the result. Input String will not be empty. For an input String: "hey You, Sort me Already!" the function should return: "You, Sort Already! hey me" """
capitals_first
def check(candidate): assert candidate('hey You, Sort me Already') == 'You, Sort Already hey me' assert candidate('sense Does to That Make you?') == 'Does That Make sense to you?' assert candidate('i First need Thing In coffee The Morning') == 'First Thing In The Morning i need coffee' assert candidate('123 baby You and Me') == 'You Me baby and' assert candidate('Life gets Sometimes pretty !Hard') == 'Life Sometimes gets pretty' check(capitals_first)
[ "assert capitals_first('hey You, Sort me Already') == 'You, Sort Already hey me'" ]
introductory
[]
APPS/2496
def day_of_the_week(day: int, month: int, year: int) -> str: """ Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. Example 1: Input: day = 31, month = 8, year = 2019 Output: "Saturday" Example 2: Input: day = 18, month = 7, year = 1999 Output: "Sunday" Example 3: Input: day = 15, month = 8, year = 1993 Output: "Sunday" Constraints: The given dates are valid dates between the years 1971 and 2100. """
day_of_the_week
def check(candidate): assert candidate(31, 8, 2019) == 'Saturday' assert candidate(18, 7, 1999) == 'Sunday' assert candidate(15, 8, 1993) == 'Sunday' check(day_of_the_week)
[ "assert day_of_the_week(31, 8, 2019) == 'Saturday'", "assert day_of_the_week(18, 7, 1999) == 'Sunday'", "assert day_of_the_week(15, 8, 1993) == 'Sunday'" ]
introductory
[]
APPS/2370
def max_length_three_blocks_palindrome(t: int, cases: List[Tuple[int, List[int]]]) -> List[int]: """ The only difference between easy and hard versions is constraints. You are given a sequence $a$ consisting of $n$ positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not. Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome. You have to answer $t$ independent test cases. Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$). -----Output----- For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome. -----Example----- Input 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 Output 7 2 4 1 1 3 """
max_length_three_blocks_palindrome
def check(candidate): assert candidate(6, [(8, [1, 1, 2, 2, 3, 2, 1, 1]), (3, [1, 3, 3]), (4, [1, 10, 10, 1]), (1, [26]), (2, [2, 1]), (3, [1, 1, 1])]) == [7, 2, 4, 1, 1, 3] check(max_length_three_blocks_palindrome)
[ "assert max_length_three_blocks_palindrome(6, [(8, [1, 1, 2, 2, 3, 2, 1, 1]), (3, [1, 3, 3]), (4, [1, 10, 10, 1]), (1, [26]), (2, [2, 1]), (3, [1, 1, 1])]) == [7, 2, 4, 1, 1, 3]" ]
introductory
[]
APPS/3791
def moment_of_time_in_space(moment: str) -> List[bool]: """ # Task You are given a `moment` in time and space. What you must do is break it down into time and space, to determine if that moment is from the past, present or future. `Time` is the sum of characters that increase time (i.e. numbers in range ['1'..'9']. `Space` in the number of characters which do not increase time (i.e. all characters but those that increase time). The moment of time is determined as follows: ``` If time is greater than space, than the moment is from the future. If time is less than space, then the moment is from the past. Otherwise, it is the present moment.``` You should return an array of three elements, two of which are false, and one is true. The true value should be at the `1st, 2nd or 3rd` place for `past, present and future` respectively. # Examples For `moment = "01:00 pm"`, the output should be `[true, false, false]`. time equals 1, and space equals 7, so the moment is from the past. For `moment = "12:02 pm"`, the output should be `[false, true, false]`. time equals 5, and space equals 5, which means that it's a present moment. For `moment = "12:30 pm"`, the output should be `[false, false, true]`. time equals 6, space equals 5, so the moment is from the future. # Input/Output - `[input]` string `moment` The moment of time and space that the input time came from. - `[output]` a boolean array Array of three elements, two of which are false, and one is true. The true value should be at the 1st, 2nd or 3rd place for past, present and future respectively. """
moment_of_time_in_space
def check(candidate): assert candidate('12:30 am') == [False, False, True] assert candidate('12:02 pm') == [False, True, False] assert candidate('01:00 pm') == [True, False, False] assert candidate('11:12 am') == [False, False, True] assert candidate('05:20 pm') == [False, False, True] assert candidate('04:20 am') == [False, True, False] check(moment_of_time_in_space)
[ "assert moment_of_time_in_space('12:02 pm') == [False, True, False]", "assert moment_of_time_in_space('12:30 am') == [False, False, True]", "assert moment_of_time_in_space('01:00 pm') == [True, False, False]" ]
introductory
[]
APPS/2444
def max_distance_between_ones(n: int) -> int: """ Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3. Example 1: Input: n = 22 Output: 2 Explanation: 22 in binary is "10110". The first adjacent pair of 1's is "10110" with a distance of 2. The second adjacent pair of 1's is "10110" with a distance of 1. The answer is the largest of these two distances, which is 2. Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined. Example 2: Input: n = 5 Output: 2 Explanation: 5 in binary is "101". Example 3: Input: n = 6 Output: 1 Explanation: 6 in binary is "110". Example 4: Input: n = 8 Output: 0 Explanation: 8 in binary is "1000". There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0. Example 5: Input: n = 1 Output: 0 Constraints: 1 <= n <= 109 """
max_distance_between_ones
def check(candidate): assert candidate(22) == 2 assert candidate(5) == 2 assert candidate(8) == 0 check(max_distance_between_ones)
[ "assert max_distance_between_ones(22) == 2", "assert max_distance_between_ones(8) == 0", "assert max_distance_between_ones(5) == 2" ]
introductory
[]
APPS/4537
def bin2gray(bits: list) -> list: """ Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps. Here is an exemple of what the code look like: ``` 0: 0000 1: 0001 2: 0011 3: 0010 4: 0110 5: 0111 6: 0101 7: 0100 8: 1100 ``` The goal of this kata is to build two function bin2gray and gray2bin wich will convert natural binary to Gray Code and vice-versa. We will use the "binary reflected Gray code". The input and output will be arrays of 0 and 1, MSB at index 0. There are "simple" formula to implement these functions. It is a very interesting exercise to find them by yourself. All input will be correct binary arrays. """
bin2gray
def check(candidate): assert candidate([1, 0, 1]) == [1, 1, 1] assert candidate([1, 1]) == [1, 0] assert candidate([1]) == [1] assert candidate([0]) == [0] assert candidate([1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]) == [1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1] assert candidate([1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]) == [1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1] check(bin2gray)
[ "assert bin2gray([1, 0, 1]) == [1, 1, 1]", "assert bin2gray([1, 1]) == [1, 0]" ]
introductory
[]
APPS/4329
def pig_latin(s: str) -> str: """ Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this kata is to wite a function that encodes a single word string to pig latin. The rules themselves are rather easy: 1) The word starts with a vowel(a,e,i,o,u) -> return the original string plus "way". 2) The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus "ay". 3) The result must be lowercase, regardless of the case of the input. If the input string has any non-alpha characters, the function must return None, null, Nothing (depending on the language). 4) The function must also handle simple random strings and not just English words. 5) The input string has no vowels -> return the original string plus "ay". For example, the word "spaghetti" becomes "aghettispay" because the first two letters ("sp") are consonants, so they are moved to the end of the string and "ay" is appended. """
pig_latin
def check(candidate): assert candidate('Hello') == 'ellohay' assert candidate('CCCC') == 'ccccay' assert candidate('tes3t5') == None assert candidate('ay') == 'ayway' assert candidate('') == None assert candidate('YA') == 'ayay' assert candidate('123') == None assert candidate('ya1') == None assert candidate('yaYAya') == 'ayayayay' assert candidate('YayayA') == 'ayayayay' check(pig_latin)
[ "assert pig_latin('spaghetti') == 'aghettispay'" ]
introductory
[]
APPS/2473
def modifyString(s: str) -> str: """ Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guaranteed that there are no consecutive repeating characters in the given string except for '?'. Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints. Example 1: Input: s = "?zs" Output: "azs" Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs". Example 2: Input: s = "ubv?w" Output: "ubvaw" Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww". Example 3: Input: s = "j?qg??b" Output: "jaqgacb" Example 4: Input: s = "??yw?ipkj?" Output: "acywaipkja" Constraints: 1 <= s.length <= 100 s contains only lower case English letters and '?'. """
modifyString
def check(candidate): assert candidate('?zs') == 'azs' assert candidate('ubv?w') == 'ubvaw' assert candidate('j?qg??b') == 'jaqgacb' assert candidate('??yw?ipkj?') == 'acywaipkja' check(modifyString)
[ "assert modifyString('?zs') == 'azs'", "assert modifyString('ubv?w') == 'ubvaw'", "assert modifyString('j?qg??b') == 'jaqgacb'", "assert modifyString('??yw?ipkj?') == 'acywaipkja'" ]
introductory
[]
APPS/2732
def blocks(s: str) -> str: """ ## Task You will receive a string consisting of lowercase letters, uppercase letters and digits as input. Your task is to return this string as blocks separated by dashes (`"-"`). The elements of a block should be sorted with respect to the hierarchy listed below, and each block cannot contain multiple instances of the same character. Elements should be put into the first suitable block. The hierarchy is: 1. lowercase letters (`a - z`), in alphabetical order 2. uppercase letters (`A - Z`), in alphabetical order 3. digits (`0 - 9`), in ascending order ## Examples * `"21AxBz" -> "xzAB12"` - since input does not contain repeating characters, you only need 1 block * `"abacad" -> "abcd-a-a"` - character "a" repeats 3 times, thus 3 blocks are needed * `"" -> ""` - an empty input should result in an empty output * `"hbh420sUUW222IWOxndjn93cdop69NICEep832" -> "bcdehjnopsxCEINOUW0234689-dhnpIUW239-2-2-2"` - a more sophisticated example Good luck! """
blocks
def check(candidate): assert candidate('heyitssampletestkk') == 'aeiklmpsty-ehkst-s' assert candidate('dasf6ds65f45df65gdf651vdf5s1d6g5f65vqweAQWIDKsdds') == 'adefgqsvwADIKQW1456-dfgsv156-dfs56-dfs56-dfs56-df56-d5-d' assert candidate('SDF45648374RHF8BFVYg378rg3784rf87g3278bdqG') == 'bdfgqrBDFGHRSVY2345678-grF3478-gF3478-3478-78-8' assert candidate('') == '' assert candidate('aaaaaaaaaa') == 'a-a-a-a-a-a-a-a-a-a' check(blocks)
[ "assert blocks('21AxBz') == 'xzAB12'", "assert blocks('abacad') == 'abcd-a-a'", "assert blocks('->') == ''" ]
introductory
[]
APPS/2863
def AlanAnnoyingKid(sentence: str) -> str: """ Alan's child can be annoying at times. When Alan comes home and tells his kid what he has accomplished today, his kid never believes him. Be that kid. Your function 'AlanAnnoyingKid' takes as input a sentence spoken by Alan (a string). The sentence contains the following structure: "Today I " + [action_verb] + [object] + "." (e.g.: "Today I played football.") Your function will return Alan's kid response, which is another sentence with the following structure: "I don't think you " + [action_performed_by_alan] + " today, I think you " + ["did" OR "didn't"] + [verb_of _action_in_present_tense] + [" it!" OR " at all!"] (e.g.:"I don't think you played football today, I think you didn't play at all!") Note the different structure depending on the presence of a negation in Alan's first sentence (e.g., whether Alan says "I dind't play football", or "I played football"). ! Also note: Alan's kid is young and only uses simple, regular verbs that use a simple "ed" to make past tense. There are random test cases. Some more examples: input = "Today I played football." output = "I don't think you played football today, I think you didn't play at all!" input = "Today I didn't attempt to hardcode this Kata." output = "I don't think you didn't attempt to hardcode this Kata today, I think you did attempt it!" input = "Today I didn't play football." output = "I don't think you didn't play football today, I think you did play it!" input = "Today I cleaned the kitchen." output = "I don't think you cleaned the kitchen today, I think you didn't clean at all!" """
AlanAnnoyingKid
def check(candidate): assert candidate('Today I played football.') == "I don't think you played football today, I think you didn't play at all!" assert candidate("Today I didn't play football.") == "I don't think you didn't play football today, I think you did play it!" assert candidate("Today I didn't attempt to hardcode this Kata.") == "I don't think you didn't attempt to hardcode this Kata today, I think you did attempt it!" assert candidate('Today I cleaned the kitchen.') == "I don't think you cleaned the kitchen today, I think you didn't clean at all!" assert candidate('Today I learned to code like a pro.') == "I don't think you learned to code like a pro today, I think you didn't learn at all!" check(AlanAnnoyingKid)
[ "assert AlanAnnoyingKid('Today I played football.') == \"I don't think you played football today, I think you didn't play at all!\"", "assert AlanAnnoyingKid(\"Today I didn't attempt to hardcode this Kata.\") == \"I don't think you didn't attempt to hardcode this Kata today, I think you did attempt it!\"", "assert AlanAnnoyingKid(\"Today I didn't play football.\") == \"I don't think you didn't play football today, I think you did play it!\"", "assert AlanAnnoyingKid('Today I cleaned the kitchen.') == \"I don't think you cleaned the kitchen today, I think you didn't clean at all!\"" ]
introductory
[]
APPS/3877
def T9(words: list, seq: str) -> list: """ The T9 typing predictor helps with suggestions for possible word combinations on an old-style numeric keypad phone. Each digit in the keypad (2-9) represents a group of 3-4 letters. To type a letter, press once the key which corresponds to the letter group that contains the required letter. Typing words is done by typing letters of the word in sequence. The letter groups and corresponding digits are as follows: ``` ----------------- | 1 | 2 | 3 | | | ABC | DEF | |-----|-----|-----| | 4 | 5 | 6 | | GHI | JKL | MNO | |-----|-----|-----| | 7 | 8 | 9 | | PQRS| TUV | WXYZ| ----------------- ``` The prediction algorithm tries to match the input sequence against a predefined dictionary of words. The combinations which appear in the dictionary are considered valid words and are shown as suggestions. Given a list of words as a reference dictionary, and a non-empty string (of digits 2-9) as input, complete the function which returns suggestions based on the string of digits, which are found in the reference dictionary. For example: ```python T9(['hello', 'world'], '43556') returns ['hello'] T9(['good', 'home', 'new'], '4663') returns ['good', 'home'] ``` Note that the dictionary must be case-insensitive (`'hello'` and `'Hello'` are same entries). The list returned must contain the word as it appears in the dictionary (along with the case). Example: ```python T9(['Hello', 'world'], '43556') returns ['Hello'] ``` If there is no prediction available from the given dictionary, then return the string containing first letters of the letter groups, which correspond to the input digits. For example: ```python T9([], '43556') returns ['gdjjm'] T9(['gold', 'word'], '4663') returns ['gmmd'] ``` """
T9
def check(candidate): assert candidate(['hello', 'world'], '43556') == ['hello'] assert candidate(['good', 'home', 'new'], '4663') == ['good', 'home'] assert candidate(['gone', 'hood', 'good', 'old'], '4663') == ['gone', 'hood', 'good'] assert candidate(['Hello', 'world'], '43556') == ['Hello'] assert candidate(['gOOD', 'hOmE', 'NeW'], '4663') == ['gOOD', 'hOmE'] assert candidate(['goNe', 'hood', 'GOOD', 'old'], '4663') == ['goNe', 'hood', 'GOOD'] assert candidate([], '43556') == ['gdjjm'] assert candidate(['gold'], '4663') == ['gmmd'] assert candidate(['gone', 'hood', 'good', 'old'], '729') == ['paw'] check(T9)
[ "assert T9(['hello', 'world'], '43556') == ['hello']", "assert T9(['good', 'home', 'new'], '4663') == ['good', 'home']", "assert T9(['Hello', 'world'], '43556') == ['Hello']", "assert T9([], '43556') == ['gdjjm']", "assert T9(['gold', 'word'], '4663') == ['gmmd']" ]
introductory
[]
APPS/2740
def wheat_from_chaff(values: list) -> list: """ # Scenario With **_Cereal crops_** like wheat or rice, before we can eat the grain kernel, we need to remove that inedible hull, or *to separate the wheat from the chaff*. ___ # Task **_Given_** a *sequence of n integers* , **_separate_** *the negative numbers (chaff) from positive ones (wheat).* ___ # Notes * **_Sequence size_** is _at least_ **_3_** * **_Return_** *a new sequence*, such that **_negative numbers (chaff) come first, then positive ones (wheat)_**. * In Java , *you're not allowed to modify the input Array/list/Vector* * **_Have no fear_** , *it is guaranteed that there will be no zeroes* . * **_Repetition_** of numbers in *the input sequence could occur* , so **_duplications are included when separating_**. * If a misplaced *positive* number is found in the front part of the sequence, replace it with the last misplaced negative number (the one found near the end of the input). The second misplaced positive number should be swapped with the second last misplaced negative number. *Negative numbers found at the head (begining) of the sequence* , **_should be kept in place_** . ____ # Input >> Output Examples: ``` wheatFromChaff ({7, -8, 1 ,-2}) ==> return ({-2, -8, 1, 7}) ``` ## **_Explanation_**: * **_Since_** `7 ` is a **_positive number_** , it should not be located at the beginnig so it needs to be swapped with the **last negative number** `-2`. ____ ``` wheatFromChaff ({-31, -5, 11 , -42, -22, -46, -4, -28 }) ==> return ({-31, -5,- 28, -42, -22, -46 , -4, 11}) ``` ## **_Explanation_**: * **_Since_**, `{-31, -5} ` are **_negative numbers_** *found at the head (begining) of the sequence* , *so we keep them in place* . * Since `11` is a positive number, it's replaced by the last negative which is `-28` , and so on till sepration is complete. ____ ``` wheatFromChaff ({-25, -48, -29, -25, 1, 49, -32, -19, -46, 1}) ==> return ({-25, -48, -29, -25, -46, -19, -32, 49, 1, 1}) ``` ## **_Explanation_**: * **_Since_** `{-25, -48, -29, -25} ` are **_negative numbers_** *found at the head (begining) of the input* , *so we keep them in place* . * Since `1` is a positive number, it's replaced by the last negative which is `-46` , and so on till sepration is complete. * Remeber, *duplications are included when separating* , that's why the number `1` appeared twice at the end of the output. ____ # Tune Your Code , There are 250 Assertions , 100.000 element For Each . # Only O(N) Complexity Solutions Will pass . ____ """
wheat_from_chaff
def check(candidate): assert candidate([2, -4, 6, -6]) == [-6, -4, 6, 2] assert candidate([7, -3, -10]) == [-10, -3, 7] assert candidate([7, -8, 1, -2]) == [-2, -8, 1, 7] assert candidate([8, 10, -6, -7, 9]) == [-7, -6, 10, 8, 9] assert candidate([-3, 4, -10, 2, -6]) == [-3, -6, -10, 2, 4] assert candidate([2, -6, -4, 1, -8, -2]) == [-2, -6, -4, -8, 1, 2] assert candidate([16, 25, -48, -47, -37, 41, -2]) == [-2, -37, -48, -47, 25, 41, 16] assert candidate([-30, -11, 36, 38, 34, -5, -50]) == [-30, -11, -50, -5, 34, 38, 36] assert candidate([-31, -5, 11, -42, -22, -46, -4, -28]) == [-31, -5, -28, -42, -22, -46, -4, 11] assert candidate([46, 39, -45, -2, -5, -6, -17, -32, 17]) == [-32, -17, -45, -2, -5, -6, 39, 46, 17] assert candidate([-9, -8, -6, -46, 1, -19, 44]) == [-9, -8, -6, -46, -19, 1, 44] assert candidate([-37, -10, -42, 19, -31, -40, -45, 33]) == [-37, -10, -42, -45, -31, -40, 19, 33] assert candidate([-25, -48, -29, -25, 1, 49, -32, -19, -46, 1]) == [-25, -48, -29, -25, -46, -19, -32, 49, 1, 1] assert candidate([-7, -35, -46, -22, 46, 43, -44, -14, 34, -5, -26]) == [-7, -35, -46, -22, -26, -5, -44, -14, 34, 43, 46] assert candidate([-46, -50, -28, -45, -27, -40, 10, 35, 34, 47, -46, -24]) == [-46, -50, -28, -45, -27, -40, -24, -46, 34, 47, 35, 10] assert candidate([-33, -14, 16, 31, 4, 41, -10, -3, -21, -12, -45, 41, -19]) == [-33, -14, -19, -45, -12, -21, -10, -3, 41, 4, 31, 41, 16] assert candidate([-17, 7, -12, 10, 4, -8, -19, -24, 40, 31, -29, 21, -45, 1]) == [-17, -45, -12, -29, -24, -8, -19, 4, 40, 31, 10, 21, 7, 1] assert candidate([-16, 44, -7, -31, 9, -43, -44, -18, 50, 39, -46, -24, 3, -34, -27]) == [-16, -27, -7, -31, -34, -43, -44, -18, -24, -46, 39, 50, 3, 9, 44] check(wheat_from_chaff)
[ "assert wheat_from_chaff([7, -8, 1 ,-2]) == [-2, -8, 1, 7]", "assert wheat_from_chaff([-31, -5, 11 , -42, -22, -46, -4, -28 ]) == [-31, -5,- 28, -42, -22, -46 , -4, 11]", "assert wheat_from_chaff([-25, -48, -29, -25, 1, 49, -32, -19, -46, 1]) == [-25, -48, -29, -25, -46, -19, -32, 49, 1, 1]" ]
introductory
[]
APPS/2505
def is_rectangle_overlap(rec1: list, rec2: list) -> bool: """ An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false. Example 1: Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] Output: true Example 2: Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] Output: false Example 3: Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3] Output: false Constraints: rect1.length == 4 rect2.length == 4 -109 <= rec1[i], rec2[i] <= 109 rec1[0] <= rec1[2] and rec1[1] <= rec1[3] rec2[0] <= rec2[2] and rec2[1] <= rec2[3] """
is_rectangle_overlap
def check(candidate): assert candidate([0, 0, 2, 2], [1, 1, 3, 3]) == True assert candidate([0, 0, 1, 1], [1, 0, 2, 1]) == False assert candidate([0, 0, 1, 1], [2, 2, 3, 3]) == False check(is_rectangle_overlap)
[ "assert is_rectangle_overlap([0, 0, 2, 2], [1, 1, 3, 3]) == True", "assert is_rectangle_overlap([0, 0, 1, 1], [1, 0, 2, 1]) == False", "assert is_rectangle_overlap([0, 0, 1, 1], [2, 2, 3, 3]) == False" ]
introductory
[]
APPS/2491
def buddy_strings(A: str, B: str) -> bool: """ Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B. Example 2: Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B. Example 3: Input: A = "aa", B = "aa" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B. Example 4: Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true Example 5: Input: A = "", B = "aa" Output: false Constraints: 0 <= A.length <= 20000 0 <= B.length <= 20000 A and B consist of lowercase letters. """
buddy_strings
def check(candidate): assert candidate('ab', 'ba') == True assert candidate('ab', 'ab') == False assert candidate('aa', 'aa') == True assert candidate('aaaaaaabc', 'aaaaaaacb') == True assert candidate('', 'aa') == False check(buddy_strings)
[ "assert buddy_strings('ab', 'ba') == True", "assert buddy_strings('ab', 'ab') == False", "assert buddy_strings('aa', 'aa') == True", "assert buddy_strings('aaaaaaabc', 'aaaaaaacb') == True", "assert buddy_strings('', 'aa') == False" ]
introductory
[]
APPS/4777
def mystery_range(s: str, n: int) -> list[int]: """ In this kata, your task is to write a function that returns the smallest and largest integers in an unsorted string. In this kata, a range is considered a finite sequence of consecutive integers. Input Your function will receive two arguments: A string comprised of integers in an unknown range; think of this string as the result when a range of integers is shuffled around in random order then joined together into a string An integer value representing the size of the range Output Your function should return the starting (minimum) and ending (maximum) numbers of the range in the form of an array/list comprised of two integers. Test Example ```python input_string = '1568141291110137' mystery_range(input_string, 10) # [6, 15] # The 10 numbers in this string are: # 15 6 8 14 12 9 11 10 13 7 # Therefore the range of numbers is from 6 to 15 ``` Technical Details The maximum size of a range will be 100 integers The starting number of a range will be: 0 < n < 100 Full Test Suite: 21 fixed tests, 100 random tests Use Python 3+ for the Python translation For JavaScript, require has been disabled and most built-in prototypes have been frozen (prototype methods can be added to Array and Function) All test cases will be valid If you enjoyed this kata, be sure to check out my other katas """
mystery_range
def check(candidate): assert candidate('1568141291110137', 10) == [6, 15] check(mystery_range)
[ "assert mystery_range('1568141291110137', 10) == [6, 15]" ]
introductory
[]
APPS/2423
def min_start_value(nums: list[int]) -> int: """ Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. Example 1: Input: nums = [-3,2,-3,4,2] Output: 5 Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2 Example 2: Input: nums = [1,2] Output: 1 Explanation: Minimum start value should be positive. Example 3: Input: nums = [1,-2,-3] Output: 5 Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100 """
min_start_value
def check(candidate): assert candidate([-3, 2, -3, 4, 2]) == 5 assert candidate([1, 2]) == 1 assert candidate([1, -2, -3]) == 5 check(min_start_value)
[ "assert min_start_value([-3, 2, -3, 4, 2]) == 5", "assert min_start_value([1,2]) == 1", "assert min_start_value([1,-2,-3]) == 5" ]
introductory
[]
APPS/2956
def encode(stg: str) -> str: """ *Translations appreciated* ## Background information The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works. In this Kata we will implement the Hamming Code with bit length 3, this has some advantages and disadvantages: - ✓ Compared to other versions of hamming code, we can correct more mistakes - ✓ It's simple to implement - x The size of the input triples ## Task 1: Encode function: First of all we have to implement the encode function, which is pretty easy, just follow the steps below. Steps: 1. convert every letter of our text to ASCII value 2. convert ASCII value to 8-bit binary string 3. replace every "0" with "000" and every "1" with "111" Let's do an example: We have to convert the string ```hey``` to hamming code sequence. 1. First convert it to ASCII values: ```104``` for ```h```, ```101``` for ```e``` and ```121``` for ```y```. 2. Now we convert the ASCII values to a 8-bit binary string: ```104``` -> ```01101000```, ```101``` -> ```01100101``` and ```121``` -> ```01111001``` if we concat the binarys we get ```011010000110010101111001``` 3. Now we replace every "0" with "000" and every "1" with "111": ```011010000110010101111001``` -> ```000111111000111000000000000111111000000111000111000111111111111000000111``` That's it good job! ## Task 2: Decode function: Now we have to check if there happened any mistakes and correct them. Errors will only be a bit flip and not a loose of bits, so the length of the input string is always divisible by 3. example: - 111 --> 101 this can and will happen - 111 --> 11 this won't happen The length of the input string is also always divsible by 24 so that you can convert it to an ASCII value. Steps: 1. Split the string of 0 and 1 in groups of three characters example: "000", "111" 2. Check if an error occured: If no error occured the group is "000" or "111", then replace "000" with "0" and "111" with 1 If an error occured the group is for example "001" or "100" or "101" and so on... Replace this group with the character that occurs most often. example: "010" -> "0" , "110" -> "1" 3. Now take a group of 8 characters and convert that binary number to decimal ASCII value 4. Convert the ASCII value to a char and well done you made it :) Look at this example carefully to understand it better: We got a bit sequence: ```100111111000111001000010000111111000000111001111000111110110111000010111``` First we split the bit sequence into groups of three: ```100```, ```111```, ```111```, ```000```, ```111```, ```001``` .... Every group with the most "0" becomes "0" and every group with the most "1" becomes "1": ```100``` -> ```0``` Because there are two ```0``` and only one ```1``` ```111``` -> ```1``` Because there are zero ```0``` and three ```1``` ```111``` -> ```1``` Because there are zero ```0``` and three ```1``` ```000``` -> ```0``` Because there are three ```0``` and zero ```1``` ```111``` -> ```1``` Because there are zero ```0``` and three ```1``` ```001``` -> ```0``` Because there are two ```0``` and one ```1``` Now concat all 0 and 1 to get ```011010000110010101111001``` We split this string into groups of eight: ```01101000```, ```01100101``` and ```01111001```. And now convert it back to letters: ```01101000``` is binary representation of 104, which is ASCII value of ```h``` ```01100101``` is binary representation of 101, which is ASCII value of ```e``` ```01111001``` is binary representation of 121, which is ASCII value of ```y``` Now we got our word ```hey``` ! """ def decode(bits: str) -> str: """ Now we have to check if there happened any mistakes and correct them. Errors will only be a bit flip and not a loss of bits, so the length of the input string is always divisible by 3. Split the string of 0 and 1 in groups of three characters. Check if an error occurred: If no error occurred the group is '000' or '111', then replace '000' with '0' and '111' with '1'. If an error occurred the group is for example '001' or '100' or '101' and so on... Replace this group with the character that occurs most often. Take a group of 8 characters and convert that binary number to decimal ASCII value. Convert the ASCII value to a character. Args: bits (str): The input string of bits to be decoded. Returns: str: The decoded string from the Hamming Code. """
encode
def check(candidate): assert candidate('hey') == '000111111000111000000000000111111000000111000111000111111111111000000111' assert candidate('The Sensei told me that i can do this kata') == '000111000111000111000000000111111000111000000000000111111000000111000111000000111000000000000000000111000111000000111111000111111000000111000111000111111000111111111000000111111111000000111111000111111000000111000111000111111000111000000111000000111000000000000000000111111111000111000000000111111000111111111111000111111000111111000000000111111000000111000000000000111000000000000000000111111000111111000111000111111000000111000111000000111000000000000000000111111111000111000000000111111000111000000000000111111000000000000111000111111111000111000000000000111000000000000000000111111000111000000111000000111000000000000000000111111000000000111111000111111000000000000111000111111000111111111000000000111000000000000000000111111000000111000000000111111000111111111111000000111000000000000000000111111111000111000000000111111000111000000000000111111000111000000111000111111111000000111111000000111000000000000000000111111000111000111111000111111000000000000111000111111111000111000000000111111000000000000111' assert candidate('T3st') == '000111000111000111000000000000111111000000111111000111111111000000111111000111111111000111000000' assert candidate('T?st!%') == '000111000111000111000000000000111111111111111111000111111111000000111111000111111111000111000000000000111000000000000111000000111000000111000111' check(encode)
[ "assert encode('hey') == '000111111000111000000000000111111000000111000111000111111111111000000111'" ]
introductory
[]
APPS/2480
def min_cost_to_move_chips(position: list[int]) -> int: """ We have n chips, where the position of the ith chip is position[i]. We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to: position[i] + 2 or position[i] - 2 with cost = 0. position[i] + 1 or position[i] - 1 with cost = 1. Return the minimum cost needed to move all the chips to the same position. Example 1: Input: position = [1,2,3] Output: 1 Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. Example 2: Input: position = [2,2,2,3,3] Output: 2 Explanation: We can move the two chips at poistion 3 to position 2. Each move has cost = 1. The total cost = 2. Example 3: Input: position = [1,1000000000] Output: 1 Constraints: 1 <= position.length <= 100 1 <= position[i] <= 10^9 """
min_cost_to_move_chips
def check(candidate): assert candidate([1, 2, 3]) == 1 assert candidate([2, 2, 2, 3, 3]) == 2 assert candidate([1, 1000000000]) == 1 check(min_cost_to_move_chips)
[ "assert min_cost_to_move_chips([1, 2, 3]) == 1", "assert min_cost_to_move_chips([2,2,2,3,3]) == 2", "assert min_cost_to_move_chips([1,1000000000]) == 1" ]
introductory
[]
APPS/4715
def build_palindrome(s: str) -> str: """ ## Task Given a string, add the fewest number of characters possible from the front or back to make it a palindrome. ## Example For the input `cdcab`, the output should be `bacdcab` ## Input/Output Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10 The output is a palindrome string satisfying the task. For s = `ab` either solution (`aba` or `bab`) will be accepted. """
build_palindrome
def check(candidate): assert candidate('abcdc') == 'abcdcba' assert candidate('ababa') == 'ababa' check(build_palindrome)
[ "assert build_palindrome('cdcab') == 'bacdcab'" ]
introductory
[]
APPS/2418
def containsDuplicate(nums: list[int]) -> bool: """ Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true """
containsDuplicate
def check(candidate): assert candidate([1, 2, 3, 1]) == True assert candidate([1, 2, 3, 4]) == False assert candidate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) == True check(containsDuplicate)
[ "assert containsDuplicate([1, 2, 3, 1]) == True", "assert containsDuplicate([1, 2, 3, 4]) == False", "assert containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) == True" ]
introductory
[]
APPS/3133
def vaccine_list(age: str, status: str, month: str) -> list[str]: """ ### Vaccinations for children under 5 You have been put in charge of administrating vaccinations for children in your local area. Write a function that will generate a list of vaccines for each child presented for vaccination, based on the child's age and vaccination history, and the month of the year. #### The function takes three parameters: age, status and month - The parameter 'age' will be given in weeks up to 16 weeks, and thereafter in months. You can assume that children presented will be scheduled for vaccination (eg '16 weeks', '12 months' etc). - The parameter 'status' indicates if the child has missed a scheduled vaccination, and the argument will be a string that says 'up-to-date', or a scheduled stage (eg '8 weeks') that has been missed, in which case you need to add any missing shots to the list. Only one missed vaccination stage will be passed in per function call. - If the month is 'september', 'october' or 'november' add 'offer fluVaccine' to the list. - Make sure there are no duplicates in the returned list, and sort it alphabetically. #### Example input and output ~~~~ input ('12 weeks', 'up-to-date', 'december') output ['fiveInOne', 'rotavirus'] input ('12 months', '16 weeks', 'june') output ['fiveInOne', 'hibMenC', 'measlesMumpsRubella', 'meningitisB', 'pneumococcal'] input ('40 months', '12 months', 'october') output ['hibMenC', 'measlesMumpsRubella', 'meningitisB', 'offer fluVaccine', 'preSchoolBooster'] ~~~~ #### To save you typing it up, here is the vaccinations list ~~~~ fiveInOne : ['8 weeks', '12 weeks', '16 weeks'], //Protects against: diphtheria, tetanus, whooping cough, polio and Hib (Haemophilus influenzae type b) pneumococcal : ['8 weeks', '16 weeks'], //Protects against: some types of pneumococcal infection rotavirus : ['8 weeks', '12 weeks'], //Protects against: rotavirus infection, a common cause of childhood diarrhoea and sickness meningitisB : ['8 weeks', '16 weeks', '12 months'], //Protects against: meningitis caused by meningococcal type B bacteria hibMenC : ['12 months'], //Protects against: Haemophilus influenzae type b (Hib), meningitis caused by meningococcal group C bacteria measlesMumpsRubella : ['12 months', '40 months'], //Protects against: measles, mumps and rubella fluVaccine : ['september','october','november'], //Given at: annually in Sept/Oct preSchoolBooster : ['40 months'] //Protects against: diphtheria, tetanus, whooping cough and polio ~~~~ """
vaccine_list
def check(candidate): assert candidate('12 weeks', 'up-to-date', 'december') == ['fiveInOne', 'rotavirus'] assert candidate('12 months', '16 weeks', 'june') == ['fiveInOne', 'hibMenC', 'measlesMumpsRubella', 'meningitisB', 'pneumococcal'] assert candidate('40 months', '12 months', 'october') == ['hibMenC', 'measlesMumpsRubella', 'meningitisB', 'offer fluVaccine', 'preSchoolBooster'] check(vaccine_list)
[ "assert vaccine_list('12 weeks', 'up-to-date', 'december') == ['fiveInOne', 'rotavirus']", "assert vaccine_list('12 months', '16 weeks', 'june') == ['fiveInOne', 'hibMenC', 'measlesMumpsRubella', 'meningitisB', 'pneumococcal']", "assert vaccine_list('40 months', '12 months', 'october') == ['hibMenC', 'measlesMumpsRubella', 'meningitisB', 'offer fluVaccine', 'preSchoolBooster']" ]
introductory
[]
APPS/2387
def max_burles_spent(t: int, test_cases: list[int]) -> list[int]: """ Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\lfloor\frac{x}{10}\rfloor$ back). The operation $\lfloor\frac{a}{b}\rfloor$ means $a$ divided by $b$ rounded down. It is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$. Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. For example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The next $t$ lines describe test cases. Each test case is given on a separate line and consists of one integer $s$ ($1 \le s \le 10^9$) — the number of burles Mishka initially has. -----Output----- For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally. -----Example----- Input 6 1 10 19 9876 12345 1000000000 Output 1 11 21 10973 13716 1111111111 """
max_burles_spent
def check(candidate): assert candidate(6, [1, 10, 19, 9876, 12345, 1000000000]) == [1, 11, 21, 10973, 13716, 1111111111] check(max_burles_spent)
[ "assert max_burles_spent(6, [1, 10, 19, 9876, 12345, 1000000000]) == [1, 11, 21, 10973, 13716, 1111111111]" ]
introductory
[]
APPS/4634
def pac_man(N: int, PM: list[int], enemies: list[list[int]]) -> int: """ # Task Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him. Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to count the number of coins he can collect without being seen. An enemy can see a Pac-Man if they are standing on the same row or column. It is guaranteed that no enemy can see Pac-Man on the starting position. There is a coin on each empty square (i.e. where there is no Pac-Man or enemy). # Example For `N = 4, PM = [3, 0], enemies = [[1, 2]]`, the result should be `3`. ``` Let O represent coins, P - Pac-Man and E - enemy. OOOO OOEO OOOO POOO``` Pac-Man cannot cross row 1 and column 2. He can only collect coins from points `(2, 0), (2, 1) and (3, 1)`, like this: ``` x is the points that Pac-Man can collect the coins. OOOO OOEO xxOO PxOO ``` # Input/Output - `[input]` integer `N` The field size. - `[input]` integer array `PM` Pac-Man's position (pair of integers) - `[input]` 2D integer array `enemies` Enemies' positions (array of pairs) - `[output]` an integer Number of coins Pac-Man can collect. # More PacMan Katas - [Play PacMan: Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136) - [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8) """
pac_man
def check(candidate): assert candidate(1, [0, 0], []) == 0 assert candidate(2, [0, 0], []) == 3 assert candidate(3, [0, 0], []) == 8 assert candidate(3, [1, 1], []) == 8 assert candidate(2, [0, 0], [[1, 1]]) == 0 assert candidate(3, [2, 0], [[1, 1]]) == 0 assert candidate(3, [2, 0], [[0, 2]]) == 3 assert candidate(10, [4, 6], [[0, 2], [5, 2], [5, 5]]) == 15 assert candidate(8, [1, 1], [[5, 4]]) == 19 assert candidate(8, [1, 5], [[5, 4]]) == 14 assert candidate(8, [6, 1], [[5, 4]]) == 7 check(pac_man)
[ "assert pac_man(1, [0, 0], []) == 0", "assert pac_man(10, [4, 6], [[0, 2], [5, 2], [5, 5]]) == 15", "assert pac_man(8, [1, 1], [[5, 4]]) == 19" ]
introductory
[]
APPS/2537
def distanceBetweenBusStops(distance: List[int], start: int, destination: int) -> int: """ A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops. Example 1: Input: distance = [1,2,3,4], start = 0, destination = 1 Output: 1 Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1. Example 2: Input: distance = [1,2,3,4], start = 0, destination = 2 Output: 3 Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. Example 3: Input: distance = [1,2,3,4], start = 0, destination = 3 Output: 4 Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. Constraints: 1 <= n <= 10^4 distance.length == n 0 <= start, destination < n 0 <= distance[i] <= 10^4 """
distanceBetweenBusStops
def check(candidate): assert candidate([1, 2, 3, 4], 0, 1) == 1 assert candidate([1, 2, 3, 4], 0, 2) == 3 assert candidate([1, 2, 3, 4], 0, 3) == 4 check(distanceBetweenBusStops)
[ "assert distanceBetweenBusStops([1, 2, 3, 4], 0, 1) == 1", "assert distanceBetweenBusStops([1, 2, 3, 4], 0, 2) == 3", "assert distanceBetweenBusStops([1, 2, 3, 4], 0, 3) == 4" ]
introductory
[]
APPS/2520
def reverse(x: int) -> int: """ Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """
reverse
def check(candidate): assert candidate(123) == 321 assert candidate(-123) == -321 assert candidate(120) == 21 check(reverse)
[ "assert reverse(123) == 321", "assert reverse(-123) == -321", "assert reverse(120) == 21" ]
introductory
[]
APPS/2394
def min_moves_to_regular_bracket_sequence(t: int, test_cases: list[tuple[int, str]]) -> list[int]: """ You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$). Your task is to find the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints. Recall what the regular bracket sequence is: "()" is regular bracket sequence; if $s$ is regular bracket sequence then "(" + $s$ + ")" is regular bracket sequence; if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($2 \le n \le 50$) — the length of $s$. It is guaranteed that $n$ is even. The second line of the test case containg the string $s$ consisting of $\frac{n}{2}$ opening and $\frac{n}{2}$ closing brackets. -----Output----- For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints. -----Example----- Input 4 2 )( 4 ()() 8 ())()()( 10 )))((((()) Output 1 0 1 3 -----Note----- In the first test case of the example, it is sufficient to move the first bracket to the end of the string. In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string. In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())". """
min_moves_to_regular_bracket_sequence
def check(candidate): assert candidate(4, [(2, ')('), (4, '()()'), (8, '())()()('), (10, ')))((((())')]) == [1, 0, 1, 3] check(min_moves_to_regular_bracket_sequence)
[ "assert min_moves_to_regular_bracket_sequence(4, [(2, ')('), (4, '()()'), (8, '())()()('), (10, ')))((((())')]) == [1, 0, 1, 3]" ]
introductory
[]
APPS/2469
def checkIfExist(arr: list[int]) -> bool: """ Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. Example 2: Input: arr = [7,1,14,11] Output: true Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. Example 3: Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M. Constraints: 2 <= arr.length <= 500 -10^3 <= arr[i] <= 10^3 """
checkIfExist
def check(candidate): assert candidate([10, 2, 5, 3]) == True assert candidate([7, 1, 14, 11]) == True assert candidate([3, 1, 7, 11]) == False check(checkIfExist)
[ "assert checkIfExist([10, 2, 5, 3]) == True", "assert checkIfExist([7, 1, 14, 11]) == True", "assert checkIfExist([3, 1, 7, 11]) == False" ]
introductory
[]
APPS/2379
def min_num_subsequences(t: int, test_cases: list[tuple[int, str]]) -> list[tuple[int, list[int]]]: """ You are given a binary string $s$ consisting of $n$ zeros and ones. Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones). Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100". You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the test case contains $n$ characters '0' and '1' — the string $s$. It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer: in the first line print one integer $k$ ($1 \le k \le n$) — the minimum number of subsequences you can divide the string $s$ to. In the second line print $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the number of subsequence the $i$-th character of $s$ belongs to. If there are several answers, you can print any. -----Example----- Input 4 4 0011 6 111111 5 10101 8 01010000 Output 2 1 2 2 1 6 1 2 3 4 5 6 1 1 1 1 1 1 4 1 1 1 1 1 2 3 4 """
min_num_subsequences
def check(candidate): assert candidate(4, [(4, '0011'), (6, '111111'), (5, '10101'), (8, '01010000')]) == [(2, [1, 2, 2, 1]), (6, [1, 2, 3, 4, 5, 6]), (1, [1, 1, 1, 1, 1]), (4, [1, 1, 1, 1, 1, 2, 3, 4])] check(min_num_subsequences)
[ "assert min_num_subsequences(4, [(4, '0011'), (6, '111111'), (5, '10101'), (8, '01010000')]) == [(2, [1, 2, 2, 1]), (6, [1, 2, 3, 4, 5, 6]), (1, [1, 1, 1, 1, 1]), (4, [1, 1, 1, 1, 1, 2, 3, 4])]" ]
introductory
[]
APPS/4255
def make_upper_case(s: str) -> str: """ Write a function which converts the input string to uppercase. ~~~if:bf For BF all inputs end with \0, all inputs are lowercases and there is no space between. ~~~ """
make_upper_case
def check(candidate): assert candidate('hello') == 'HELLO' assert candidate('hello world') == 'HELLO WORLD' assert candidate('hello world !') == 'HELLO WORLD !' assert candidate('heLlO wORLd !') == 'HELLO WORLD !' assert candidate('1,2,3 hello world!') == '1,2,3 HELLO WORLD!' check(make_upper_case)
[ "assert make_upper_case('hello world !') == 'HELLO WORLD !'" ]
introductory
[]
APPS/3843
def encrypt(text: str) -> str: """ For encrypting strings this region of chars is given (in this order!): * all letters (ascending, first all UpperCase, then all LowerCase) * all digits (ascending) * the following chars: `.,:;-?! '()$%&"` These are 77 chars! (This region is zero-based.) Write two methods: ```python def encrypt(text) def decrypt(encrypted_text) ``` Prechecks: 1. If the input-string has chars, that are not in the region, throw an Exception(C#, Python) or Error(JavaScript). 2. If the input-string is null or empty return exactly this value! For building the encrypted string: 1. For every second char do a switch of the case. 2. For every char take the index from the region. Take the difference from the region-index of the char before (from the input text! Not from the fresh encrypted char before!). (Char2 = Char1-Char2) Replace the original char by the char of the difference-value from the region. In this step the first letter of the text is unchanged. 3. Replace the first char by the mirror in the given region. (`'A' -> '"'`, `'B' -> '&'`, ...) Simple example: * Input: `"Business"` * Step 1: `"BUsInEsS"` * Step 2: `"B61kujla"` * `B -> U` * `B (1) - U (20) = -19` * `-19 + 77 = 58` * `Region[58] = "6"` * `U -> s` * `U (20) - s (44) = -24` * `-24 + 77 = 53` * `Region[53] = "1"` * Step 3: `"&61kujla"` This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-) """ def decrypt(encrypted_text: str) -> str: """ The reverse process of the encryption described above. """
encrypt
def check(candidate): assert candidate('$-Wy,dM79H\'i\'o$n0C&I.ZTcMJw5vPlZc Hn!krhlaa:khV mkL;gvtP-S7Rt1Vp2RV:wV9VuhO Iz3dqb.U0w') == 'Do the kata "Kobayashi-Maru-Test!" Endless fun and excitement when finding a solution!' assert candidate('5MyQa9p0riYplZc') == 'This is a test!' assert candidate('5MyQa79H\'ijQaw!Ns6jVtpmnlZ.V6p') == 'This kata is very interesting!' assert candidate('') == '' assert candidate(None) == None check(encrypt)
[ "assert encrypt('$-Wy,dM79H\\'i\\'o$n0C&I.ZTcMJw5vPlZc Hn!krhlaa:khV mkL;gvtP-S7Rt1Vp2RV:wV9VuhO Iz3dqb.U0w') == 'Do the kata \"Kobayashi-Maru-Test!\" Endless fun and excitement when finding a solution!'" ]
introductory
[]
APPS/2431
def find_unique_k_diff_pairs(arr: list[int], k: int) -> int: """ Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input:[1, 2, 3, 4, 5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: [1, 3, 1, 5, 4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1). Note: The pairs (i, j) and (j, i) count as the same pair. The length of the array won't exceed 10,000. All the integers in the given input belong to the range: [-1e7, 1e7]. """
find_unique_k_diff_pairs
def check(candidate): assert candidate([3, 1, 4, 1, 5], 2) == 2 assert candidate([1, 2, 3, 4, 5], 1) == 4 assert candidate([1, 3, 1, 5, 4], 0) == 1 check(find_unique_k_diff_pairs)
[ "assert find_unique_k_diff_pairs([3, 1, 4, 1, 5], 2) == 2", "assert find_unique_k_diff_pairs([1, 2, 3, 4, 5], 1) == 4", "assert find_unique_k_diff_pairs([1, 3, 1, 5, 4], 0) == 1" ]
introductory
[]
APPS/1545
def check_parity_QC(n: int, cases: List[Tuple[int, int]]) -> List[int]: """ The Quark Codejam's number QC(n, m) represents the number of ways to partition a set of n things into m nonempty subsets. For example, there are seven ways to split a four-element set into two parts: {1, 2, 3} ∪ {4}, {1, 2, 4} ∪ {3}, {1, 3, 4} ∪ {2}, {2, 3, 4} ∪ {1}, {1, 2} ∪ {3, 4}, {1, 3} ∪ {2, 4}, {1, 4} ∪ {2, 3}. We can compute QC(n, m) using the recurrence, QC(n, m) = mQC(n − 1, m) + QC(n − 1, m − 1), for integers 1 < m < n. but your task is a somewhat different: given integers n and m, compute the parity of QC(n, m), i.e. QC(n, m) mod 2. Example : QC(4, 2) mod 2 = 1. Write a program that reads two positive integers n and m, computes QC(n, m) mod 2, and writes the result. -----Input----- The input begins with a single positive integer on a line by itself indicating the number of the cases. This line is followed by the input cases. The input consists two integers n and m separated by a space, with 1 ≤ m ≤ n ≤ 1000000000. -----Output----- For each test case, print the output. The output should be the integer S(n, m) mod 2. Sample Input 1 4 2 Sample Output 1 """
check_parity_QC
def check(candidate): assert candidate(1, [(4, 2)]) == [1] check(check_parity_QC)
[ "assert check_parity_QC(1, [(4, 2)]) == [1]" ]
interview
[]
APPS/910
def calculate_scales(T: int, test_cases: List[Tuple[str, int]]) -> List[int]: """ Recently, Chef got obsessed with piano. He is a just a rookie in this stuff and can not move his fingers from one key to other fast enough. He discovered that the best way to train finger speed is to play scales. There are different kinds of scales which are divided on the basis of their interval patterns. For instance, major scale is defined by pattern T-T-S-T-T-T-S, where ‘T’ stands for a whole tone whereas ‘S’ stands for a semitone. Two semitones make one tone. To understand how they are being played, please refer to the below image of piano’s octave – two consecutive keys differ by one semitone. If we start playing from first key (note C), then we’ll play all white keys in a row (notes C-D-E-F-G-A-B-C – as you can see C and D differ for a tone as in pattern, and E and F differ for a semitone). This pattern could be played some number of times (in cycle). Each time Chef takes some type of a scale and plays using some number of octaves. Sometimes Chef can make up some scales, so please don’t blame him if you find some scale that does not exist in real world. Formally, you have a set of 12 keys (i.e. one octave) and you have N such sets in a row. So in total, you have 12*N keys. You also have a pattern that consists of letters 'T' and 'S', where 'T' means move forward for two keys (from key x to key x + 2, and 'S' means move forward for one key (from key x to key x + 1). Now, you can start playing from any of the 12*N keys. In one play, you can repeat the pattern as many times as you want, but you cannot go outside the keyboard. Repeating pattern means that if, for example, you have pattern STTST, you can play STTST as well as STTSTSTTST, as well as STTSTSTTSTSTTST, as well as any number of repeating. For this pattern, if you choose to repeat it once, if you start at some key x, you'll press keys: x (letter 'S')-> x + 1 (letter 'T')-> x + 3 (letter 'T')-> x + 5 (letter 'S') -> x + 6 (letter 'T')-> x + 8. Also 1 ≤ x, x + 8 ≤ 12*N so as to avoid going off the keyboard. You are asked to calculate number of different plays that can be performed. Two plays differ if and only if they start at different keys or patterns are repeated different number of times. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case contains scale’s pattern – string s consisting of letters ‘T’ and ‘S’ only. Second line contains one integer N – number of octaves he’ll be using. -----Output----- For each test case output a single number in a line corresponding to number of different scales he’ll play. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ |S| ≤ 100 - 1 ≤ n ≤ 7 -----Subtasks----- Subtask 1: T < 10 4, N = 1 Subtask 2: No additional constraints. -----Example----- Input: 2 TTTT 1 TTSTTTS 3 Output: 4 36 -----Explanation----- Example case 1. In the first case there is only one octave and Chef can play scale (not in cycle each time) starting with notes C, C#, D, D# - four together. """
calculate_scales
def check(candidate): assert candidate(2, [('TTTT', 1), ('TTSTTTS', 3)]) == [4, 36] check(calculate_scales)
[ "assert calculate_scales(2, [('TTTT', 1), ('TTSTTTS', 3)]) == [4, 36]" ]
interview
[]
APPS/1037
def pawn_chess(T: int, test_cases: List[str]) -> List[str]: """ Ada is playing pawn chess with Suzumo. Pawn chess is played on a long board with N$N$ squares in one row. Initially, some of the squares contain pawns. Note that the colours of the squares and pawns do not matter in this game, but otherwise, the standard chess rules apply: - no two pawns can occupy the same square at the same time - a pawn cannot jump over another pawn (they are no knights!), i.e. if there is a pawn at square i$i$, then it can only be moved to square i−2$i-2$ if squares i−1$i-1$ and i−2$i-2$ are empty - pawns cannot move outside of the board (outs are forbidden) The players alternate turns; as usual, Ada plays first. In each turn, the current player must choose a pawn and move it either one or two squares to the left of its current position. The player that cannot make a move loses. Can Ada always beat Suzumo? Remember that Ada is a chess grandmaster, so she always plays optimally. -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first and only line of each test case contains a single string S$S$ with length N$N$ describing the initial board from left to right. An empty square and a square containing a pawn are denoted by the characters '.' and 'P' respectively. -----Output----- For each test case, print a single line containing the string "Yes" if Ada wins the game or "No" otherwise (without quotes). -----Constraints----- - 1≤T≤500$1 \le T \le 500$ - 2≤N≤128$2 \le N \le 128$ - S$S$ contains only characters '.' and 'P' -----Example Input----- 1 ..P.P -----Example Output----- Yes -----Explanation----- Example case 1: Ada can move the first pawn two squares to the left; the board after this move looks like P...P and now, Suzumo can only move the second pawn. If he moves it one square to the left, Ada will move it two squares to the left on her next move, and if he moves it two squares to the left, Ada will move it one square to the left, so the board after Ada's next move will look like PP... and Suzumo cannot make any move here. """
pawn_chess
def check(candidate): assert candidate(1, ['..P.P']) == ['Yes'] check(pawn_chess)
[ "assert pawn_chess(1, ['..P.P']) == ['Yes']" ]
interview
[]
APPS/1562
def minimize_m(T: int, test_cases: List[Tuple[int, List[int]]]) -> List[int]: """ "I'm a fan of anything that tries to replace actual human contact." - Sheldon. After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact. He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact. Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer k$k$. - Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ . -----Output:----- For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$ and 0$0$ <= mi$m_i$<= ni$n_i$ . If no such answer exists print -1. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤k≤1000$1 \leq k \leq 1000$ - 1≤ni≤10$1 \leq n_i \leq 10$18$18$ -----Sample Input:----- 1 1 5 -----Sample Output:----- 2 -----EXPLANATION:----- 5$5$C$C$2$2$ = 10 which is even and m is minimum. """
minimize_m
def check(candidate): assert candidate(1, [(1, [5])]) == [2] check(minimize_m)
[ "assert minimize_m(1, [(1, [5])]) == [2]" ]
interview
[]
APPS/749
def min_additional_cost(N: int, costs: List[List[int]]) -> int: """ The Government of Siruseri is no different from any other when it comes to being "capital-centric" in its policies. Recently the government decided to set up a nationwide fiber-optic network to take Siruseri into the digital age. And as usual, this decision was implemented in a capital centric manner --- from each city in the country, a fiber optic cable was laid to the capital! Thus, traffic between any two cities had to go through the capital. Soon, it became apparent that this was not quite a clever idea, since any breakdown at the capital resulted in the disconnection of services between other cities. So, in the second phase, the government plans to connect a few more pairs of cities directly by fiber-optic cables. The government has specified that this is to be done in such a way that the disruption of services at any one city will still leave the rest of the country connected. The government has data on the cost of laying fiber optic cables between every pair of cities. You task is to compute the minimum cost of additional cabling required to ensure the requirement described above is met. For example, if Siruseri has $4$ cities numbered $1,2,3$ and $4$ where $1$ is the capital and further suppose that the cost of laying cables between these cities are as given in the table below: Note that the government has already connected the capital with every other city. So, if we connect the cities $2$ and $3$ as well as $3$ and $4$, you can check that disruption of service at any one city will still leave the other cities connected. The cost of connecting these two pairs is $4 + 6 = 10$. The same effect could have been achieved by connecting $2$ and $3$ as well as $2$ and $4$, which would have cost $4 + 5 = 9$. You can check that this is the best you can do. Your task is to write a program that allows the government to determine the minimum cost it has to incur in laying additional cables to fulfil the requirement. -----Input:----- - The first line of the input contains a single integer $N$ indicating the number of cities in Siruseri. You may assume that the capital city is always numbered $1$. - This is followed by $N$ lines of input each containing $N$ integers. - The $j^{th}$ integer on line $i$ is the cost of connecting city $i$ with city $j$. The $j^{th}$ integer on line $i$ will be the same as the $i^{th}$ integer on line $j$ (since the links are bidirectional) and the $i^{th}$ entry on line $i$ will always be $0$ (there is no cost in connecting a city with itself). -----Output:----- A single integer indicating the minimum total cost of the links to be added to ensure that disruption of services at one city does not disconnect the rest of the cities. -----Constraints:----- - $1 \leq N \leq 2000$. - $0 \leq$ costs given in the input $\leq 100000$ -----Sample Input----- 4 0 7 8 10 7 0 4 5 8 4 0 6 10 5 6 0 -----Sample Output----- 9 """
min_additional_cost
def check(candidate): assert candidate(4, [[0, 7, 8, 10], [7, 0, 4, 5], [8, 4, 0, 6], [10, 5, 6, 0]]) == 9 check(min_additional_cost)
[ "assert min_additional_cost(4, [[0, 7, 8, 10], [7, 0, 4, 5], [8, 4, 0, 6], [10, 5, 6, 0]]) == 9" ]
interview
[]
APPS/613
def count_bubbly_words(M: int, words: List[str]) -> int: """ -----Problem----- Nikki's latest work is writing a story of letters. However, she finds writing story so boring that, after working for three hours, she realized that all she has written are M long words consisting entirely of letters A and B. Having accepted that she will never finish the story in time, Nikki has decided to at least have some fun with it by counting bubbly words. Now Nikki is connecting pairs of identical letters (A with A, B with B) by drawing lines above the word. A given word is bubbly if each letter can be connected to exactly one other letter in such a way that no two lines intersect. So here is your task. Help Nikki count how many words are bubbly. -----Input----- - The first line of input contains the positive integer M, the number of words written down by Nikki. - Each of the following M lines contains a single word consisting of letters A and B, with length between 2 and 10^5, inclusive. The sum of lengths of all words doesn't exceed 10^6. -----Output----- The first and only line of output must contain the number of bubbly words. -----Constraints----- - 1 ≤ M ≤ 100 -----Sample Input----- 3 ABAB AABB ABBA -----Sample Output----- 2 -----Explanation----- - ABAB - It is not bubbly as A(indexed 1) will connect to A(indexed 3) by a line and when we try to connect B(indexed 2) with B(indexed 4) by a line then it will intersect with the line b/w A and A. - AABB - It is bubbly as line b/w A and A will not intersect with the line b/w B and B. - ABBA -It is also bubbly as lines will not intersect. We can draw line b/w A and A above the line b/w B and B. p { text-align:justify } """
count_bubbly_words
def check(candidate): assert candidate(3, ['ABAB', 'AABB', 'ABBA']) == 2 check(count_bubbly_words)
[ "assert count_bubbly_words(3, ['ABAB', 'AABB', 'ABBA']) == 2" ]
interview
[]
APPS/837
def sum_of_multiples(T: int, test_cases: List[int]) -> List[int]: """ Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow) -----Input----- Input will start with an integer T the count of test cases, each case will have an integer N. -----Output----- Output each values, on a newline. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤1000000000 -----Example----- Input: 1 10 Output: 10 -----Explanation----- Example case 1. Only integer that is multiple 10 that is less than or equal to 10 is 10 """
sum_of_multiples
def check(candidate): assert candidate(1, [10]) == [10] assert candidate(2, [10, 20]) == [10, 30] assert candidate(1, [1]) == [0] assert candidate(3, [30, 40, 50]) == [60, 100, 150] check(sum_of_multiples)
[ "assert sum_of_multiples(1, [10]) == [10]" ]
interview
[]
APPS/725
def avoid_arrest(T: int, test_cases: List[Tuple[int, int, int, List[int]]]) -> List[int]: """ The Little Elephant and his friends from the Zoo of Lviv were returning from the party. But suddenly they were stopped by the policeman Big Hippo, who wanted to make an alcohol test for elephants. There were N elephants ordered from the left to the right in a row and numbered from 0 to N-1. Let R[i] to be the result of breathalyzer test of i-th elephant. Considering current laws in the Zoo, elephants would be arrested if there exists K consecutive elephants among them for which at least M of these K elephants have the maximal test result among these K elephants. Using poor math notations we can alternatively define this as follows. The elephants would be arrested if there exists i from 0 to N-K, inclusive, such that for at least M different values of j from i to i+K-1, inclusive, we have R[j] = max{R[i], R[i+1], ..., R[i+K-1]}. The Big Hippo is very old and the Little Elephant can change some of the results. In a single operation he can add 1 to the result of any elephant. But for each of the elephants he can apply this operation at most once. What is the minimum number of operations that the Little Elephant needs to apply, such that the sequence of results, after all operations will be applied, let elephants to avoid the arrest? If it is impossible to avoid the arrest applying any number of operations, output -1. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space-separated integers N, K, M. The second line contains N space-separated integers R[0], R[1], ..., R[N-1] denoting the test results of the elephants. -----Output----- For each test case, output a single line containing the minimum number of operations needed to avoid the arrest. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ M ≤ K ≤ N ≤ 17 - 1 ≤ R[i] ≤ 17 -----Example----- Input: 4 5 3 2 1 3 1 2 1 5 3 3 7 7 7 7 7 5 3 3 7 7 7 8 8 4 3 1 1 3 1 2 Output: 0 1 1 -1 -----Explanation----- Example case 1. Let's follow the poor math definition of arrest. We will consider all values of i from 0 to N-K = 2, inclusive, and should count the number of values of j described in the definition. If it less than M = 2 then this value of i does not cause the arrest, otherwise causes.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1 we have R[j] = maxConclusioni=0{1, 3, 1}max = 3R[j] = 3 for j = 1does not cause the arresti=1{3, 1, 2}max = 3R[j] = 3 for j = 1does not cause the arresti=2{1, 2, 1}max = 2R[j] = 2 for j = 3does not cause the arrest So we see that initial test results of the elephants do not cause their arrest. Hence the Little Elephant does not need to apply any operations. Therefore, the answer is 0. Example case 2.We have N = 5, K = 3, M = 3. Let's construct similar table as in example case 1. Here the value of i will cause the arrest if we have at least 3 values of j described in the definition.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1 we have R[j] = maxConclusioni=0{7, 7, 7}max = 7R[j] = 7 for j = 0, 1, 2causes the arresti=1{7, 7, 7}max = 7R[j] = 7 for j = 1, 2, 3causes the arresti=2{7, 7, 7}max = 7R[j] = 7 for j = 2, 3, 4causes the arrest So we see that for initial test results of the elephants each value of i causes their arrest. Hence the Little Elephant needs to apply some operations in order to avoid the arrest. He could achieve his goal by adding 1 to the result R[2]. Then results will be {R[0], R[1], R[2], R[3], R[4]} = {7, 7, 8, 7, 7}. Let's check that now elephants will be not arrested.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1 we have R[j] = maxConclusioni=0{7, 7, 8}max = 8R[j] = 8 for j = 2does not cause the arresti=1{7, 8, 7}max = 8R[j] = 8 for j = 2does not cause the arresti=2{8, 7, 7}max = 8R[j] = 8 for j = 2does not cause the arrest So we see that now test results of the elephants do not cause their arrest. Thus we see that using 0 operations we can't avoid the arrest but using 1 operation can. Hence the answer is 1. Example case 3.We have N = 5, K = 3, M = 3. Let's construct similar table as in example case 1. Here the value of i will cause the arrest if we have at least 3 values of j described in the definition.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1 we have R[j] = maxConclusioni=0{7, 7, 7}max = 7R[j] = 7 for j = 0, 1, 2causes the arresti=1{7, 7, 8}max = 8R[j] = 8 for j = 3does not cause the arresti=2{7, 8, 8}max = 8R[j] = 8 for j = 3, 4does not cause the arrest So we see that for initial test results of the elephants the value of i = 0 causes their arrest. Hence the Little Elephant needs to apply some operations in order to avoid the arrest. He could achieve his goal by adding 1 to the result R[1]. Then results will be {R[0], R[1], R[2], R[3], R[4]} = {7, 8, 7, 8, 8}. Let's check that now elephants will be not arrested.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1 we have R[j] = maxConclusioni=0{7, 8, 7}max = 8R[j] = 8 for j = 1does not cause the arresti=1{8, 7, 8}max = 8R[j] = 8 for j = 1, 3does not cause the arresti=2{7, 8, 8}max = 8R[j] = 8 for j = 3, 4does not cause the arrest So we see that now test results of the elephants do not cause their arrest. Thus we see that using 0 operations we can't avoid the arrest but using 1 operation can. Hence the answer is 1. Note that if we increase by 1 the result R[2] instead of R[1] then the value i = 2 will cause the arrest since {R[2], R[3], R[4]} will be {8, 8, 8} after this operation and we will have 3 values of j from 2 to 4, inclusive, for which R[j] = max{R[2], R[3], R[4]}, namely, j = 2, 3, 4. Example case 4. When M = 1 the Little Elephant can't reach the goal since for each value of i from 0 to N-K we have at least one value of j for which R[j] = max{R[i], R[i+1], ..., R[i+K-1]}. """
avoid_arrest
def check(candidate): assert candidate(4, [(5, 3, 2, [1, 3, 1, 2, 1]), (5, 3, 3, [7, 7, 7, 7, 7]), (5, 3, 3, [7, 7, 7, 8, 8]), (4, 3, 1, [1, 3, 1, 2])]) == [0, 1, 1, -1] check(avoid_arrest)
[ "assert avoid_arrest(4, [(5, 3, 2, [1, 3, 1, 2, 1]), (5, 3, 3, [7, 7, 7, 7, 7]), (5, 3, 3, [7, 7, 7, 8, 8]), (4, 3, 1, [1, 3, 1, 2])]) == [0, 1, 1, -1]" ]
interview
[]
APPS/753
def max_nice_bouquet(T: int, test_cases: List[Tuple[List[int], List[int], List[int]]]) -> List[int]: """ It's autumn now, the time of the leaf fall. Sergey likes to collect fallen leaves in autumn. In his city, he can find fallen leaves of maple, oak and poplar. These leaves can be of three different colors: green, yellow or red. Sergey has collected some leaves of each type and color. Now he wants to create the biggest nice bouquet from them. He considers the bouquet nice iff all the leaves in it are either from the same type of tree or of the same color (or both). Moreover, he doesn't want to create a bouquet with even number of leaves in it, since this kind of bouquets are considered to attract bad luck. However, if it's impossible to make any nice bouquet, he won't do anything, thus, obtaining a bouquet with zero leaves. Please help Sergey to find the maximal number of leaves he can have in a nice bouquet, which satisfies all the above mentioned requirements. Please note that Sergey doesn't have to use all the leaves of the same color or of the same type. For example, if he has 20 maple leaves, he can still create a bouquet of 19 leaves. -----Input----- IThe first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows." The first line of each test case contains three space-separated integers MG MY MR denoting the number of green, yellow and red maple leaves respectively. The second line contains three space-separated integers OG OY OR denoting the number of green, yellow and red oak leaves respectively. The third line of each test case contains three space-separated integers PG PY PR denoting the number of green, yellow and red poplar leaves respectively. -----Output----- For each test case, output a single line containing the maximal amount of flowers in nice bouquet, satisfying all conditions or 0 if it's impossible to create any bouquet, satisfying the conditions. -----Constraints----- - 1 ≤ T ≤ 10000 - Subtask 1 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 5 - Subtask 2 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 109 -----Example----- Input:1 1 2 3 3 2 1 1 3 4 Output:7 -----Explanation----- Example case 1. We can create a bouquet with 7 leaves, for example, by collecting all yellow leaves. This is not the only way to create the nice bouquet with 7 leaves (for example, Sergey can use all but one red leaves), but it is impossible to create a nice bouquet with more than 7 leaves. """
max_nice_bouquet
def check(candidate): assert candidate(1, [([1, 2, 3], [3, 2, 1], [1, 3, 4])]) == [7] check(max_nice_bouquet)
[ "assert max_nice_bouquet(1, [([1, 2, 3], [3, 2, 1], [1, 3, 4])]) == [7]" ]
interview
[]
APPS/1419
def max_gcd_of_tracks(T: int, test_cases: List[Tuple[int, str, Tuple[int, int, int]]]) -> List[int]: """ Mr. Wilson was planning to record his new Progressive Rock music album called "Digits. Cannot. Separate". Xenny and PowerShell, popular pseudo-number-theoreticists from the Land of Lazarus were called by him to devise a strategy to ensure the success of this new album. Xenny and Powershell took their Piano Lessons and arrived at the Studio in different Trains. Mr. Wilson, creative as usual, had created one single, long music track S. The track consisted of N musical notes. The beauty of each musical note was represented by a decimal digit from 0 to 9. Mr. Wilson told them that he wanted to create multiple musical tracks out of this long song. Since Xenny and Powershell were more into the number theory part of music, they didn’t know much about their real workings. Mr. Wilson told them that a separator could be placed between 2 digits. After placing separators, the digits between 2 separators would be the constituents of this new track and the number formed by joining them together would represent the Quality Value of that track. He also wanted them to make sure that no number formed had greater than M digits. Mr. Wilson had Y separators with him. He wanted Xenny and PowerShell to use at least X of those separators, otherwise he would have to ask them to Drive Home. Xenny and PowerShell knew straight away that they had to put place separators in such a way that the Greatest Common Divisor (GCD) of all the Quality Values would eventually determine the success of this new album. Hence, they had to find a strategy to maximize the GCD. If you find the maximum GCD of all Quality Values that can be obtained after placing the separators, Xenny and PowerShell shall present you with a Porcupine Tree. Note: - You can read about GCD here. - Greatest Common Divisor of 0 and 0 is defined as 0. -----Input----- The first line of input consists of a single integer T - the number of testcases. Each test case is of the following format: First line contains a single integer N - the length of the long musical track. Second line contains the string of digits S. Third line contains 3 space-separated integers - M, X and Y - the maximum number of digits in a number, the minimum number of separators to be used and the maximum number of separators to be used. -----Output----- For each testcase, output a single integer on a new line - the maximum GCD possible after placing the separators. -----Constraints----- Subtask 1: 20 points - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 18 - 1 ≤ M ≤ 2 - 1 ≤ X ≤ Y ≤ (N - 1) Subtask 2: 80 points - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 300 - 1 ≤ M ≤ 10 - 1 ≤ X ≤ Y ≤ (N - 1) For both Subtask 1 and Subtask 2: - 1 ≤ X ≤ Y ≤ (N - 1) - M*(Y+1) ≥ N - S may contain leading 0s. -----Example-----Input: 2 3 474 2 1 1 34 6311861109697810998905373107116111 10 4 25 Output: 2 1 -----Explanation----- Test case 1. Since only 1 separator can be placed, we can only have 2 possibilities: a. 4 | 74 The GCD in this case is 2. b. 47 | 4 The GCD in this case is 1. Hence, the maximum GCD is 2. Test case 2. One of the optimal partitions is: 63|118|61|109|69|78|109|98|90|53|73|107|116|111 Bonus: Decode the above partition to unlock a hidden treasure. """
max_gcd_of_tracks
def check(candidate): assert candidate(2, [(3, '474', (2, 1, 1)), (34, '6311861109697810998905373107116111', (10, 4, 25))]) == [2, 1] check(max_gcd_of_tracks)
[ "assert max_gcd_of_tracks(2, [(3, '474', (2, 1, 1)), (34, '6311861109697810998905373107116111', (10, 4, 25))]) == [2, 1]" ]
interview
[]
APPS/669
def count_trips(T: int, test_cases: List[Tuple[int, int, int, List[Tuple[int, int]], int, List[Tuple[int, int]]]]) -> List[int]: """ Nadaca is a country with N$N$ cities. These cities are numbered 1$1$ through N$N$ and connected by M$M$ bidirectional roads. Each city can be reached from every other city using these roads. Initially, Ryan is in city 1$1$. At each of the following K$K$ seconds, he may move from his current city to an adjacent city (a city connected by a road to his current city) or stay at his current city. Ryan also has Q$Q$ conditions (a1,b1),(a2,b2),…,(aQ,bQ)$(a_1, b_1), (a_2, b_2), \ldots, (a_Q, b_Q)$ meaning that during this K$K$-second trip, for each valid i$i$, he wants to be in city ai$a_i$ after exactly bi$b_i$ seconds. Since you are very good with directions, Ryan asked you to tell him how many different trips he could make while satisfying all conditions. Compute this number modulo 109+7$10^9 + 7$. A trip is a sequence of Ryan's current cities after 1,2,…,K$1, 2, \ldots, K$ seconds. -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains three space-separated integers N$N$, M$M$ and K$K$. - Each of the next M$M$ lines contains two space-separated integers u$u$ and v$v$ denoting a road between cities u$u$ and v$v$. - The next line contains a single integer Q$Q$. - Q$Q$ lines follow. For each i$i$ (1≤i≤Q$1 \le i \le Q$), the i$i$-th of these lines contains two space-separated integers ai$a_i$ and bi$b_i$. -----Output----- For each test case, print a single line containing one integer — the number of trips Ryan can make, modulo 109+7$10^9+7$. -----Constraints----- - 1≤T≤50$1 \le T \le 50$ - 1≤N,M,K,Q≤9,000$1 \le N, M, K, Q \le 9,000$ - 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$ - ui≠vi$u_i \neq v_i$ for each valid i$i$ - there is at most one road between each pair of cities - each city is reachable from every other city - 1≤ai≤N$1 \le a_i \le N$ for each valid i$i$ - 0≤bi≤K$0 \le b_i \le K$ for each valid i$i$ - the sum of N$N$ over all test cases does not exceed 9,000$9,000$ - the sum of K$K$ over all test cases does not exceed 9,000$9,000$ - the sum of M$M$ over all test cases does not exceed 9,000$9,000$ - the sum of Q$Q$ over all test cases does not exceed 9,000$9,000$ -----Subtasks----- Subtask #1 (20 points): - the sum of N$N$ over all test cases does not exceed 400$400$ - the sum of K$K$ over all test cases does not exceed 400$400$ - the sum of M$M$ over all test cases does not exceed 400$400$ - the sum of Q$Q$ over all test cases does not exceed 400$400$ Subtask #2 (80 points): original constraints -----Example Input----- 3 4 3 3 1 2 1 3 1 4 0 4 3 3 1 2 1 3 1 4 1 2 2 4 3 3 1 2 1 3 1 4 1 2 1 -----Example Output----- 28 4 6 """
count_trips
def check(candidate): assert candidate(3, [ (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 0, []), (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 1, [(2, 2)]), (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 1, [(2, 1)]) ]) == [28, 4, 6] check(count_trips)
[ "assert count_trips(3, [\n (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 0, []),\n (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 1, [(2, 2)]),\n (4, 3, 3, [(1, 2), (1, 3), (1, 4)], 1, [(2, 1)])\n]) == [28, 4, 6]\n" ]
interview
[]
APPS/1095
def min_moves_to_sort(N: int, books: List[int]) -> int: """ Indraneel has to sort the books in his library. His library has one long shelf. His books are numbered $1$ through $N$ and he wants to rearrange the books so that they appear in the sequence $1,2, ..., N$. He intends to do this by a sequence of moves. In each move he can pick up any book from the shelf and insert it at a different place in the shelf. Suppose Indraneel has $5$ books and they are initially arranged in the order 21453214532 \quad 1 \quad 4 \quad 5 \quad 3 Indraneel will rearrange this in ascending order by first moving book $1$ to the beginning of the shelf to get 12453124531 \quad 2 \quad 4 \quad 5 \quad 3 Then, moving book $3$ to position $3$, he gets 12345123451 \quad 2 \quad 3 \quad 4 \quad 5 Your task is to write a program to help Indraneel determine the minimum number of moves that are necessary to sort his book shelf. -----Input:----- The first line of the input will contain a single integer $N$ indicating the number of books in Indraneel's library. This is followed by a line containing a permutation of $1, 2, ..., N$ indicating the intial state of Indraneel's book-shelf. -----Output:----- A single integer indicating the minimum number of moves necessary to sort Indraneel's book-shelf. -----Constraints:----- - $1 \leq N \leq 200000$. - You may also assume that in $50 \%$ of the inputs, $1 \leq N \leq 5000$. -----Sample Input----- 5 2 1 4 5 3 -----Sample Output----- 2 """
min_moves_to_sort
def check(candidate): assert candidate(5, [2, 1, 4, 5, 3]) == 2 check(min_moves_to_sort)
[ "assert min_moves_to_sort(5, [2, 1, 4, 5, 3]) == 2" ]
interview
[]
APPS/407
def score_of_parentheses(S: str) -> int: """ Given a balanced parentheses string S, compute the score of the string based on the following rule: () has score 1 AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. Example 1: Input: "()" Output: 1 Example 2: Input: "(())" Output: 2 Example 3: Input: "()()" Output: 2 Example 4: Input: "(()(()))" Output: 6 Note: S is a balanced parentheses string, containing only ( and ). 2 <= S.length <= 50 """
score_of_parentheses
def check(candidate): assert candidate('()') == 1 assert candidate('(())') == 2 assert candidate('()()') == 2 assert candidate('(()(()))') == 6 check(score_of_parentheses)
[ "assert score_of_parentheses('()') == 1", "assert score_of_parentheses('(())') == 2", "assert score_of_parentheses('()()') == 2", "assert score_of_parentheses('(()(()))') == 6" ]
interview
[]
APPS/1591
def factorial_modulo(T: int, numbers: List[int]) -> List[int]: """ Master Oogway has forseen that a panda named Po will be the dragon warrior, and the master of Chi. But he did not tell anyone about the spell that would make him the master of Chi, and has left Po confused. Now Po has to defeat Kai, who is the super villian, the strongest of them all. Po needs to master Chi, and he finds a spell which unlocks his powerful Chi. But the spell is rather strange. It asks Po to calculate the factorial of a number! Po is very good at mathematics, and thinks that this is very easy. So he leaves the spell, thinking it's a hoax. But little does he know that this can give him the ultimate power of Chi. Help Po by solving the spell and proving that it's not a hoax. -----Input----- First line of input contains an integer T denoting the number of test cases. The next T lines contain an integer N. -----Output----- For each test case, print a single line containing the solution to the spell which is equal to factorial of N, i.e. N!. Since the output could be large, output it modulo 1589540031(Grand Master Oogway's current age). -----Constraints----- - 1 ≤ T ≤ 100000 - 1 ≤ N ≤ 100000 -----Example----- Input: 4 1 2 3 4 Output: 1 2 6 24 """
factorial_modulo
def check(candidate): assert candidate(4, [1, 2, 3, 4]) == [1, 2, 6, 24] check(factorial_modulo)
[ "assert factorial_modulo(4, [1, 2, 3, 4]) == [1, 2, 6, 24]" ]
interview
[]
APPS/820
def expected_cost(T: int, test_cases: List[Tuple[int, int, List[Tuple[int, int]]]]) -> List[float]: """ The Little Elephant from the Zoo of Lviv is going to the Birthday Party of the Big Hippo tomorrow. Now he wants to prepare a gift for the Big Hippo. He has N balloons, numbered from 1 to N. The i-th balloon has the color Ci and it costs Pi dollars. The gift for the Big Hippo will be any subset (chosen randomly, possibly empty) of the balloons such that the number of different colors in that subset is at least M. Help Little Elephant to find the expected cost of the gift. -----Input----- The first line of the input contains a single integer T - the number of test cases. T test cases follow. The first line of each test case contains a pair of integers N and M. The next N lines contain N pairs of integers Ci and Pi, one pair per line. -----Output----- In T lines print T real numbers - the answers for the corresponding test cases. Your answer will considered correct if it has at most 10^-6 absolute or relative error. -----Constraints----- - 1 ≤ T ≤ 40 - 1 ≤ N, Ci≤ 40 - 1 ≤ Pi ≤ 1000000 - 0 ≤ M ≤ K, where K is the number of different colors in the test case. -----Example----- Input: 2 2 2 1 4 2 7 2 1 1 4 2 7 Output: 11.000000000 7.333333333 """
expected_cost
def check(candidate): assert abs(candidate(2, [(2, 2, [(1, 4), (2, 7)]), (2, 1, [(1, 4), (2, 7)])]) - [11.000000000, 7.333333333]) < 1e-6 check(expected_cost)
[ "assert abs(expected_cost(2, [(2, 2, [(1, 4), (2, 7)]), (2, 1, [(1, 4), (2, 7)])]) - [11.000000000, 7.333333333]) < 1e-6" ]
interview
[]
APPS/992
def minimum_cost_to_seal(T: int, test_cases: List[Tuple[int, List[Tuple[int, int]], int, List[Tuple[int, int]]]]) -> List[int]: """ January and February are usually very cold in ChefLand. The temperature may reach -20 and even -30 degrees Celsius. Because of that, many people seal up windows in their houses. Sergey also lives in ChefLand. He wants to seal the window in his house. The window has the shape of a simple convex polygon with N vertices. For the sealing, there are M kinds of sticky stripes, which are sold in the shops. The stripe of the ith type has the length of Li millimeters and the cost of Ci rubles. The sealing process consists in picking the stripe and sticking it on the border of the window. The stripe can't be cut (it is made of very lasting material) and can only be put straight, without foldings. It is not necessary to put the strip strictly on the window border, it can possibly extend outside the border side of window too (by any possible amount). The window is considered sealed up if every point on its' border is covered with at least one stripe. Now Sergey is curious about the stripes he needs to buy. He wonders about the cheapest cost, at which he can seal his window. Please help him. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of number of vertices in the polygon denoting Sergey's window. Each of the following N lines contains a pair of space-separated integer numbers Xi Yi, denoting the coordinates of the ith points. The following line contains a single integer M denoting the number of types of sticky stripe which is sold in the shop. Each of the following M lines contains a pair of space-separated integers Li Ci denoting the length and the cost of the sticky stripe of the ith type respectively. -----Output----- For each test case, output a single line containing the minimum cost of sealing up the window. -----Constraints----- - 1 ≤ T ≤ 10 - The coordinates of the window are given either in clockwise or in a counter-clockwise order. - No three or more vertices lie on the same line (i.e. are collinear). - 0 ≤ Xi, Yi ≤ 106 - 1 ≤ Li, Ci ≤ 106 -----Subtasks----- - Subtask #1 (17 points): 3 ≤ N ≤ 10, M = 1 - Subtask #2 (24 points): 3 ≤ N ≤ 42, M ≤ 2 - Subtask #3 (59 points): 3 ≤ N ≤ 2000, 1 ≤ M ≤ 10 -----Example----- Input:1 4 0 0 1000 0 1000 2000 0 2000 2 1000 10 2000 15 Output:50 -----Explanation----- Example case 1. In this case, Sergey's window is a rectangle with the side lengths of 1000 and 2000. There are two types of the sticky stripes in the shop - the one of the length 1000 with the cost of 10 rubles and with the length of 2000 and the cost of 15 rubles. The optimal solution would be to buy 2 stripes of the first type 2 stripes of the second type. The cost will be 2 × 15 + 2 × 10 = 50 rubles. """
minimum_cost_to_seal
def check(candidate): assert candidate(1, [(4, [(0, 0), (1000, 0), (1000, 2000), (0, 2000)], 2, [(1000, 10), (2000, 15)])]) == [50] check(minimum_cost_to_seal)
[ "assert minimum_cost_to_seal(1, [(4, [(0, 0), (1000, 0), (1000, 2000), (0, 2000)], 2, [(1000, 10), (2000, 15)])]) == [50]" ]
interview
[]
APPS/1427
def calculate_distances(N: int, M: int, catchers: List[Tuple[int, int]], S: str) -> List[int]: """ Today, puppy Tuzik is going to a new dog cinema. He has already left his home and just realised that he forgot his dog-collar! This is a real problem because the city is filled with catchers looking for stray dogs. A city where Tuzik lives in can be considered as an infinite grid, where each cell has exactly four neighbouring cells: those sharing a common side with the cell. Such a property of the city leads to the fact, that the distance between cells (xA, yA) and (xB, yB) equals |xA - xB| + |yA - yB|. Initially, the puppy started at the cell with coordinates (0, 0). There are N dog-catchers located at the cells with the coordinates (xi, yi), where 1 ≤ i ≤ N. Tuzik's path can be described as a string S of M characters, each of which belongs to the set {'D', 'U', 'L', 'R'} (corresponding to it moving down, up, left, and right, respectively). To estimate his level of safety, Tuzik wants to know the sum of the distances from each cell on his path to all the dog-catchers. You don't need to output this sum for the staring cell of the path (i.e. the cell with the coordinates (0, 0)). -----Input----- The first line of the input contains two integers N and M. The following N lines contain two integers xi and yi each, describing coordinates of the dog-catchers. The last line of the input contains string S of M characters on the set {'D', 'U', 'L', 'R'}. - 'D' - decrease y by 1 - 'U' - increase y by 1 - 'L' - decrease x by 1 - 'R' - increase x by 1 -----Output----- Output M lines: for each cell of the path (except the starting cell), output the required sum of the distances. -----Constraints----- - 1 ≤ N ≤ 3 ✕ 105 - 1 ≤ M ≤ 3 ✕ 105 - -106 ≤ xi, yi ≤ 106 -----Example----- Input: 2 3 1 2 0 1 RDL Output: 4 6 6 -----Explanation----- Initially Tuzik stays at cell (0, 0). Let's consider his path: - Move 'R' to the cell (1, 0). Distance to the catcher (1, 2) equals 2, distance to the catcher (0, 1) equals 2, so the total distance equals 4 - Move 'D' to the cell (1, -1). Distance to the catcher (1, 2) equals 3, distance to the catcher (0, 1) equals 3, so the total distance equals 6 - Move 'L' to the cell (0, -1). Distance to the catcher (1, 2) equals 4, distance to the catcher (0, 1) equals 2, so the total distance equals 6 """
calculate_distances
def check(candidate): assert candidate(2, 3, [(1, 2), (0, 1)], 'RDL') == [4, 6, 6] check(calculate_distances)
[ "assert calculate_distances(2, 3, [(1, 2), (0, 1)], 'RDL') == [4, 6, 6]" ]
interview
[]
APPS/1090
def shortest_subsequence_length(T: int, test_cases: List[Tuple[int, int, List[int]]]) -> List[int]: """ You are given a sequence of n integers a1, a2, ..., an and an integer d. Find the length of the shortest non-empty contiguous subsequence with sum of elements at least d. Formally, you should find the smallest positive integer k with the following property: there is an integer s (1 ≤ s ≤ N-k+1) such that as + as+1 + ... + as+k-1 ≥ d. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains two space-separated integers n and d. - The second line contains n space-separated integers a1, a2, ..., an. -----Output----- For each test case, print a single line containing one integer — the length of the shortest contiguous subsequence with sum of elements ≥ d. If there is no such subsequence, print -1 instead. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ n ≤ 105 - -109 ≤ d ≤ 109 - -104 ≤ ai ≤ 104 - 1 ≤ sum of n over all test cases ≤ 2 · 105 -----Example----- Input: 2 5 5 1 2 3 1 -5 5 1 1 2 3 1 -5 Output: 2 1 """
shortest_subsequence_length
def check(candidate): assert candidate(2, [(5, 5, [1, 2, 3, 1, -5]), (5, 1, [1, 2, 3, 1, -5])]) == [2, 1] check(shortest_subsequence_length)
[ "assert shortest_subsequence_length(2, [(5, 5, [1, 2, 3, 1, -5]), (5, 1, [1, 2, 3, 1, -5])]) == [2, 1]" ]
interview
[]
APPS/968
def find_path_costs(N: int, parents: List[int], values: List[int]) -> List[int]: """ You are given a rooted tree on N vertices. The nodes are numbered from 1 to N, and Node 1 is the root. Each node u has an associated value attached to it: Au. For each vertex v, we consider the path going upwards from v to the root. Suppose that path is v1, v2, .., vk, where v1 = v and vk = 1. The cost of any node on this path is equal to the minimum value among all the nodes to its left in the path sequence, including itself. That is, cost(vi) = min1 <= j <= i{Avj}. And the cost of the path is the sum of costs of all the nodes in it. For every node in the tree, find the cost of the path from that node to the root. -----Input----- - The first line of the input contains a single integer, N, denoting the number of nodes in the tree. - The next line contains N-1 integers, the i-th of which denotes the parent of node i+1. - The next line contains N integers, the i-th of which denotes Ai. -----Output----- Output a single line containing N integers, the i-th of which should be the cost of the path from node i to the root. -----Constraints----- - 1 ≤ N ≤ 100,000 - -1,000,000,000 ≤ Av ≤ 1,000,000,000 -----Subtasks----- - Subtask #1 (30 points): 1 ≤ N ≤ 2000 - Subtask #2 (70 points): Original constraints. -----Example----- Input: 8 1 1 1 1 5 8 6 1 2 3 4 5 15 70 10 Output: 1 3 4 5 6 21 96 26 -----Explanation----- For example, take a look at the path from vertex 7: The path is 7 -> 8 -> 6 -> 5 -> 1. Cost(7) has no choice but to be A7. So Cost(7) = 70. Cost(8) will be minimum of A7 and A8, which turns out to be A8. So Cost(8) = 10. Cost(6) = minimum {A7, A8, A6} = minimum {70, 10, 15} = 10. Cost(5) = minimum {70, 10, 15, 5} = 5. Cost(1) = minimum {70, 10, 15, 5, 1} = 1. So, the cost of the path from 7 to the root is 70 + 10 + 10 + 5 + 1 = 96. """
find_path_costs
def check(candidate): assert candidate(8, [1, 1, 1, 1, 5, 8, 6], [1, 2, 3, 4, 5, 15, 70, 10]) == [1, 3, 4, 5, 6, 21, 96, 26] check(find_path_costs)
[ "assert find_path_costs(8, [1, 1, 1, 1, 5, 8, 6], [1, 2, 3, 4, 5, 15, 70, 10]) == [1, 3, 4, 5, 6, 21, 96, 26]" ]
interview
[]
APPS/1467
def min_lies(t: int, test_cases: List[Tuple[int, List[Tuple[str, int, str]]]]) -> List[int]: """ Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints. Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints. After the last game, they had the following little conversation: - [Alice] Johnny, you keep cheating! - [Johnny] Indeed? You cannot prove it. - [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times. So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice. -----Input----- The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow. Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form: operator li logical_value where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise. -----Output----- For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game. -----Example----- Input: 3 2 < 100 No > 100 No 3 < 2 Yes > 4 Yes = 3 No 6 < 2 Yes > 1 Yes = 1 Yes = 1 Yes > 1 Yes = 1 Yes Output: 0 1 2 Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1. """
min_lies
def check(candidate): assert candidate(3, [(2, [('<', 100, 'No'), ('>', 100, 'No')]), (3, [('<', 2, 'Yes'), ('>', 4, 'Yes'), ('=', 3, 'No')]), (6, [('<', 2, 'Yes'), ('>', 1, 'Yes'), ('=', 1, 'Yes'), ('=', 1, 'Yes'), ('>', 1, 'Yes'), ('=', 1, 'Yes')])]) == [0, 1, 2] check(min_lies)
[ "assert min_lies(3, [(2, [('<', 100, 'No'), ('>', 100, 'No')]), (3, [('<', 2, 'Yes'), ('>', 4, 'Yes'), ('=', 3, 'No')]), (6, [('<', 2, 'Yes'), ('>', 1, 'Yes'), ('=', 1, 'Yes'), ('=', 1, 'Yes'), ('>', 1, 'Yes'), ('=', 1, 'Yes')])]) == [0, 1, 2]" ]
interview
[]
APPS/646
def min_string_length(T: int, test_cases: List[str]) -> List[int]: """ Given a string $s$. You can perform the following operation on given string any number of time. Delete two successive elements of the string if they are same. After performing the above operation you have to return the least possible length of the string. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, a string $s$. -----Output:----- For each testcase, output in a single line answer- minimum length of string possible after performing given operations. -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq length of string \leq 10^5$ $s$ contains only lowercase letters. -----Sample Input:----- 3 abccd abbac aaaa -----Sample Output:----- 3 1 0 -----EXPLANATION:----- - In first case, $"abd"$ will be final string. - in second case, $"c"$ will be final string """
min_string_length
def check(candidate): assert candidate(3, ['abccd', 'abbac', 'aaaa']) == [3, 1, 0] check(min_string_length)
[ "assert min_string_length(3, ['abccd', 'abbac', 'aaaa']) == [3, 1, 0]" ]
interview
[]
APPS/1561
def generate_tiles(T: int, cases: List[int]) -> List[str]: """ Chef Tobby asked Bhuvan to brush up his knowledge of statistics for a test. While studying some distributions, Bhuvan learns the fact that for symmetric distributions, the mean and the median are always the same. Chef Tobby asks Bhuvan out for a game and tells him that it will utilize his new found knowledge. He lays out a total of 109 small tiles in front of Bhuvan. Each tile has a distinct number written on it from 1 to 109. Chef Tobby gives Bhuvan an integer N and asks him to choose N distinct tiles and arrange them in a line such that the mean of median of all subarrays lies between [N-1, N+1], both inclusive. The median of subarray of even length is the mean of the two numbers in the middle after the subarray is sorted Bhuvan realizes that his book didn’t teach him how to solve this and asks for your help. Can you solve the problem for him? In case, no solution exists, print -1. -----Input section----- First line contains, T, denoting the number of test cases. Each of the next T lines, contain a single integer N. -----Output section----- If no solution, exists print -1. If the solution exists, output N space separated integers denoting the elements of the array A such that above conditions are satisfied. In case, multiple answers exist, you can output any one them. -----Input constraints----- 1 ≤ T ≤ 20 1 ≤ N ≤ 100 -----Sample Input----- 3 1 2 3 -----Sample Output----- 1 1 2 1 2 3 -----Explanation----- For test case 3, the subarrays and their median are as follows: - {1}, median = 1 - {2}, median = 2 - {3}, median = 3 - {1, 2}, median = 1.5 - {2, 3}, median = 2.5 - {1, 2, 3}, median = 2 The mean of the medians is 2 which lies in the range [2, 4] """
generate_tiles
def check(candidate): assert candidate(3, [1, 2, 3]) == ['1', '1 2', '1 2 3'] check(generate_tiles)
[ "assert generate_tiles(3, [1, 2, 3]) == ['1', '1 2', '1 2 3']" ]
interview
[]
APPS/1348
def shortest_average_path(T: int, test_cases: List[Tuple[int, int, List[Tuple[int, int, int]], Tuple[int, int]]]) -> List[float]: """ There are a lot of problems related to the shortest paths. Nevertheless, there are not much problems, related to the shortest paths in average. Consider a directed graph G, consisting of N nodes and M edges. Consider a walk from the node A to the node B in this graph. The average length of this walk will be total sum of weight of its' edges divided by number of edges. Every edge counts as many times as it appears in this path. Now, your problem is quite simple. For the given graph and two given nodes, find out the shortest average length of the walk between these nodes. Please note, that the length of the walk need not to be finite, but average walk length will be. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a pair of space-separated integers N and M denoting the number of nodes and the number of edges in the graph. Each of the following M lines contains a triple of space-separated integers Xi Yi Zi, denoting the arc, connecting the node Xi to the node Yi (but not vice-versa!) having the weight of Zi. The next line contains a pair of space separated integers A and B, denoting the first and the last node of the path. -----Output----- For each test case, output a single line containing the length of the shortest path in average. If there is no path at all, output just -1 on the corresponding line of the output. -----Constraints----- - 1 ≤ N ≤ 500 - 1 ≤ M ≤ 1000 - A is not equal to B - 1 ≤ A, B, Xi, Yi ≤ N - 1 ≤ Zi ≤ 100 - There are no self-loops and multiple edges in the graph. - 1 ≤ sum of N over all test cases ≤ 10000 - 1 ≤ sum of M over all test cases ≤ 20000 -----Subtasks----- - Subtask #1 (45 points): 1 ≤ N ≤ 10, 1 ≤ M ≤ 20; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-2. - Subtask #2 (55 points): no additional constraints; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-6. -----Example----- Input:2 3 3 1 2 1 2 3 2 3 2 3 1 3 3 3 1 2 10 2 3 1 3 2 1 1 3 Output:1.5 1.0 -----Explanation----- Example case 1. The walk 1 -> 2 and 2 -> 3 has average length of 3/2 = 1.5. Any other walks in the graph will have more or equal average length than this. """
shortest_average_path
def check(candidate): assert candidate(2, [(3, 3, [(1, 2, 1), (2, 3, 2), (3, 2, 3)], (1, 3)), (3, 3, [(1, 2, 10), (2, 3, 1), (3, 2, 1)], (1, 3))]) == [1.5, 1.0] check(shortest_average_path)
[ "assert shortest_average_path(2, [(3, 3, [(1, 2, 1), (2, 3, 2), (3, 2, 3)], (1, 3)), (3, 3, [(1, 2, 10), (2, 3, 1), (3, 2, 1)], (1, 3))]) == [1.5, 1.0]" ]
interview
[]
APPS/451
def check_reducible_anagrams(S: str, T: str) -> bool: """ Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. In general a rational number can be represented using up to three parts: an integer part, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways: <IntegerPart> (e.g. 0, 12, 123) <IntegerPart><.><NonRepeatingPart>  (e.g. 0.5, 1., 2.12, 2.0001) <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212)) The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets.  For example: 1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66) Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6. Example 1: Input: S = "0.(52)", T = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2: Input: S = "0.1666(6)", T = "0.166(66)" Output: true Example 3: Input: S = "0.9(9)", T = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "". Note: Each part consists only of digits. The <IntegerPart> will not begin with 2 or more zeros.  (There is no other restriction on the digits of each part.) 1 <= <IntegerPart>.length <= 4 0 <= <NonRepeatingPart>.length <= 4 1 <= <RepeatingPart>.length <= 4 """
check_reducible_anagrams
def check(candidate): assert candidate("0.(52)", "0.5(25)") == True assert candidate("0.1666(6)", "0.166(66)") == True assert candidate("0.9(9)", "1.") == True check(check_reducible_anagrams)
[ "assert check_reducible_anagrams(\"0.(52)\", \"0.5(25)\") == True", "assert check_reducible_anagrams(\"0.1666(6)\", \"0.166(66)\") == True", "assert check_reducible_anagrams(\"0.9(9)\", \"1.\") == True" ]
interview
[]
APPS/1072
def check_reducible_anagrams(T: int, N: List[int]) -> List[str]: """ Problem description. Winston and Royce love sharing memes with each other. They express the amount of seconds they laughed ar a meme as the number of ‘XD’ subsequences in their messages. Being optimization freaks, they wanted to find the string with minimum possible length and having exactly the given number of ‘XD’ subsequences. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. - Next T lines contains a single integer N, the no of seconds laughed. -----Output----- - For each input, print the corresponding string having minimum length. If there are multiple possible answers, print any. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 109 - 1 ≤ Sum of length of output over all testcases ≤ 5*105 -----Example----- Input: 1 9 Output: XXXDDD -----Explanation----- Some of the possible strings are - XXDDDXD,XXXDDD,XDXXXDD,XDXDXDD etc. Of these, XXXDDD is the smallest. """
check_reducible_anagrams
def check(candidate): assert candidate(1, [9]) == ['XXXDDD'] check(check_reducible_anagrams)
[ "assert check_reducible_anagrams(1, [9]) == ['XXXDDD']" ]
interview
[]
APPS/299
def min_cost(grid: List[List[int]]) -> int: """ Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some invalid signs on the cells of the grid which points outside the grid. You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path. Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1 Example 4: Input: grid = [[2,2,2],[2,2,2]] Output: 3 Example 5: Input: grid = [[4]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 """
min_cost
def check(candidate): assert candidate([[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]) == 3 assert candidate([[1,1,3],[3,2,2],[1,1,4]]) == 0 assert candidate([[1,2],[4,3]]) == 1 assert candidate([[2,2,2],[2,2,2]]) == 3 assert candidate([[4]]) == 0 check(min_cost)
[ "assert min_cost([[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]) == 3", "assert min_cost([[1,1,3],[3,2,2],[1,1,4]]) == 0", "assert min_cost([[1,2],[4,3]]) == 1", "assert min_cost([[2,2,2],[2,2,2]]) == 3", "assert min_cost([[4]]) == 0" ]
interview
[]
APPS/1565
def find_A_from_B(T: int, test_cases: List[Tuple[int, int, int, List[List[List[int]]]]]) -> List[List[List[int]]]: """ Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagonally opposite vertices. In other word (i, j, k) in B is the sum of numbers of A having coordinates (a, b, c) such that 0 ≤ a ≤ i, 0 ≤ b ≤ j, 0 ≤ c ≤ k. The problem is that given B, you have to find out A. -----Input----- The first line of input will contain the number of test cases ( ≤ 10). That many test cases will follow in subsequent lines. The first line of each test case will contain the numbers X Y Z (0 ≤ X, Y, Z ≤ 100). After that there will be X x Y lines each containing Z numbers of B. The first line contains the numbers (0, 0, 0), (0, 0, 1)..., (0, 0, Z-1). The second line has the numbers (0, 1, 0), (0, 1, 1)..., (0, 1, Z-1) and so on. The (Y+1)th line will have the numbers (1, 0, 0), (1, 0, 1)..., (1, 0, Z-1) and so on. -----Output----- For each test case print the numbers of A in exactly the same fashion as the input. -----Example----- Input: 2 3 1 1 1 8 22 1 2 3 0 9 13 18 45 51 Output: 1 7 14 0 9 4 18 18 2 """
find_A_from_B
def check(candidate): assert candidate(2, [(3, 1, 1, [[[1]], [[8]], [[22]]]), (1, 2, 3, [[[0, 9, 13], [18, 45, 51]]])]) == [[[1], [7], [14]], [[0, 9, 4], [18, 18, 2]]] check(find_A_from_B)
[ "assert find_A_from_B(2, [(3, 1, 1, [[[1]], [[8]], [[22]]]), (1, 2, 3, [[[0, 9, 13], [18, 45, 51]]])]) == [[[1], [7], [14]], [[0, 9, 4], [18, 18, 2]]]" ]
interview
[]
APPS/1314
def game_outcome(N: int, M: int, A: List[int], games: List[Tuple[str, int, str]]) -> str: """ Devu and Churu love to play games a lot. Today, they have an array A consisting of N positive integers. First they listed all N × (N+1) / 2 non-empty continuous subarrays of the array A on a piece of paper and then replaced all the subarrays on the paper with the maximum element present in the respective subarray. Devu and Churu decided to play a game with numbers on the paper. They both have decided to make moves turn by turn. In one turn, the player picks some number from the list and discards that number. The one who is not able to make a valid move will be the loser. To make the game more interesting, they decided to put some constraints on their moves. A constraint on a game can be any of following three types : - > K : They are allowed to choose numbers having values strictly greater than K only. - < K : They are allowed to choose numbers having values strictly less than K only. - = K : They are allowed to choose numbers having values equal to K only. Given M constraints and who goes first, you have to tell the outcome of each game. Print 'D' if Devu wins otherwise print 'C' without quotes. Note that M games are independent, that is, they'll rewrite numbers by using array A after each game. (This is the task for the loser of the previous game!) -----Input ----- First line of input contains two space separated integers N and M denoting the size of array A and number of game played by them. Next line of input contains N space-separated integers denoting elements of array A. Each of the next M lines of input contains three space-separated parameters describing a game. First two parameter are a character C ∈ {<, >, =} and an integer K denoting the constraint for that game. The last parameter is a character X ∈ {D, C} denoting the player who will start the game. ----- Output ----- Output consists of a single line containing a string of length M made up from characters D and C only, where ith character in the string denotes the outcome of the ith game. ----- Constraints: ----- - 1 ≤ N, M ≤ 106 - 1 ≤ Ai, K ≤ 109 - X ∈ {D, C} - C ∈ {<, >, =} -----Subtasks: ----- - Subtask 1 : 1 ≤ N, M ≤ 104 : ( 20 pts ) - Subtask 2 : 1 ≤ N, M ≤ 105 : ( 30 pts ) - Subtask 3 : 1 ≤ N, M ≤ 106 : ( 50 pts ) -----Example:----- Input: 3 5 1 2 3 > 1 D < 2 C = 3 D > 4 C < 5 D Output: DCDDC -----Explanation: ----- Subarray List : - [1] - [2] - [3] - [1,2] - [2,3] - [1,2,3] Numbers on the paper after replacement : - [1] - [2] - [3] - [2] - [3] - [3] Game 1 : There are only 5 numbers > 1 in the list. Game 2 : There is only 1 number < 2 in the list. Game 3 : There are only 3 numbers = 3 in the list. Game 4 : There are no numbers > 4 in the list. So the first player cannot make his move. Game 5 : There are 6 numbers < 5 in the list. """
game_outcome
def check(candidate): assert candidate(3, 5, [1, 2, 3], [('>', 1, 'D'), ('<', 2, 'C'), ('=', 3, 'D'), ('>', 4, 'C'), ('<', 5, 'D')]) == 'DCDDC' check(game_outcome)
[ "assert game_outcome(3, 5, [1, 2, 3], [('>', 1, 'D'), ('<', 2, 'C'), ('=', 3, 'D'), ('>', 4, 'C'), ('<', 5, 'D')]) == 'DCDDC'" ]
interview
[]
APPS/986
def arrange_buildings(T: int, test_cases: List[Tuple[int, int]]) -> List[str]: """ Problem Statement:Captain America and Iron Man are at WAR and the rage inside Iron Man is rising. But Iron Man faces a problem to identify the location of Captain America. There are N buildings situtaed adjacently to each other and Captain America can be at any building. Iron Man has to arrange the Buildings from 1 to N is such a way that Value(i.e abs(Building Number -Position of Building))=K for every building. Can You help Iron Man to Find The Arrangement of the Buildings? P.S- If no arrangement exist, then print “CAPTAIN AMERICA EVADES”. Input Format: The first line of input contains a single integer,T, denoting the number of test cases. Each of the T subsequent lines contains 2 space-separated integers describing the respective N and K values for a test case. Output Format: On a new line for each test case, Print the lexicographically smallest arrangement; If no absolute arrangement exists, print “CAPTAIN AMERICA EVADES”. Constraints: SubTask#1 1<=T<=10 1<=N<=10^5 0<=K<=N SubTask#2 Original Constraints.. SubTask#3 Original Constraints.. Sample Input: 3 2 1 3 0 3 2 Sample Output: 2 1 1 2 3 CAPTAIN AMERICA EVADES Explanation: Case 1: N=2 and K=1 Therefore the arrangement is [2,1]. Case 2: N=3 and K=0 Therefore arrangement is [1,2,3]. """
arrange_buildings
def check(candidate): assert candidate(3, [(2, 1), (3, 0), (3, 2)]) == ['2 1', '1 2 3', 'CAPTAIN AMERICA EVADES'] check(arrange_buildings)
[ "assert arrange_buildings(3, [(2, 1), (3, 0), (3, 2)]) == ['2 1', '1 2 3', 'CAPTAIN AMERICA EVADES']" ]
interview
[]
APPS/549
def min_cuts_sky_scrapers(n: int, heights: List[int]) -> int: """ In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order. -----Input----- *First line of input is the number of sky-scrappers in the city *Second line of input is the height of the respective sky-scrappers -----Output----- * Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order. -----Example----- Input: 5 1 2 3 4 5 Output: 8 By: Chintan,Asad,Ashayam,Akanksha """
min_cuts_sky_scrapers
def check(candidate): assert candidate(5, [1, 2, 3, 4, 5]) == 8 check(min_cuts_sky_scrapers)
[ "assert min_cuts_sky_scrapers(5, [1, 2, 3, 4, 5]) == 8" ]
interview
[]
APPS/558
def earliest_arrival_time(M: int, N: int, rows: List[Tuple[str, int]], cols: List[Tuple[str, int]], start: Tuple[int, int, int], destination: Tuple[int, int]) -> int: """ The city of Siruseri is impeccably planned. The city is divided into a rectangular array of cells with $M$ rows and $N$ columns. Each cell has a metro station. There is one train running left to right and back along each row, and one running top to bottom and back along each column. Each trains starts at some time $T$ and goes back and forth along its route (a row or a column) forever. Ordinary trains take two units of time to go from one station to the next. There are some fast trains that take only one unit of time to go from one station to the next. Finally, there are some slow trains that take three units of time to go from one station the next. You may assume that the halting time at any station is negligible. Here is a description of a metro system with $3$ rows and $4$ columns: $ $ S(1) F(2) O(2) F(4) F(3) . . . . S(2) . . . . O(2) . . . . $ $ The label at the beginning of each row/column indicates the type of train (F for fast, O for ordinary, S for slow) and its starting time. Thus, the train that travels along row 1 is a fast train and it starts at time $3$. It starts at station ($1$, $1$) and moves right, visiting the stations along this row at times $3, 4, 5$ and $6$ respectively. It then returns back visiting the stations from right to left at times $6, 7, 8$ and $9$. It again moves right now visiting the stations at times $9, 10, 11$ and $12$, and so on. Similarly, the train along column $3$ is an ordinary train starting at time $2$. So, starting at the station ($3$,$1$), it visits the three stations on column $3$ at times $2, 4$ and $6$, returns back to the top of the column visiting them at times $6,8$ and $10$, and so on. Given a starting station, the starting time and a destination station, your task is to determine the earliest time at which one can reach the destination using these trains. For example suppose we start at station ($2$,$3$) at time $8$ and our aim is to reach the station ($1$,$1$). We may take the slow train of the second row at time $8$ and reach ($2$,$4$) at time $11$. It so happens that at time $11$, the fast train on column $4$ is at ($2$,$4$) travelling upwards, so we can take this fast train and reach ($1$,$4$) at time $12$. Once again we are lucky and at time $12$ the fast train on row $1$ is at ($1$,$4$), so we can take this fast train and reach ($1$, $1$) at time $15$. An alternative route would be to take the ordinary train on column $3$ from ($2$,$3$) at time $8$ and reach ($1$,$3$) at time $10$. We then wait there till time $13$ and take the fast train on row $1$ going left, reaching ($1$,$1$) at time $15$. You can verify that there is no way of reaching ($1$,$1$) earlier than that. -----Input:----- The first line contains two integers $M$ and $N$ indicating the number rows and columns in the metro system. This is followed by $M$ lines, lines $2, 3, …, M+1$, describing the trains along the $M$ rows. The first letter on each line is either F or O or S, indicating whether the train is a fast train, an ordinary train or a slow train. Following this, separated by a blank space, is an integer indicating the time at which this train starts running. The next $N$ lines, lines $M+2, M+3, …, N+M+1$, contain similar descriptions of the trains along the $N$ columns. The last line, line $N+M+2$, contains $5$ integers $a, b, c, d$ and $e$ where ($a$,$b$) is the starting station, $c$ is the starting time and ($d$,$e$) is the destination station. -----Output:----- A single integer indicating the earliest time at which one may reach the destination. -----Constraints:----- - $1 \leq M, N \leq 50$. - $1 \leq a, d \leq M$ - $1 \leq b, e \leq N$ - $1 \leq$ all times in input $\leq 20$ -----Sample Input----- 3 4 F 3 S 2 O 2 S 1 F 2 O 2 F 4 2 3 8 1 1 -----Sample Output----- 15 """
earliest_arrival_time
def check(candidate): assert candidate(3, 4, [('F', 3), ('S', 2), ('O', 2)], [('S', 1), ('F', 2), ('O', 2), ('F', 4)], (2, 3, 8), (1, 1)) == 15 check(earliest_arrival_time)
[ "assert earliest_arrival_time(3, 4, [('F', 3), ('S', 2), ('O', 2)], [('S', 1), ('F', 2), ('O', 2), ('F', 4)], (2, 3, 8), (1, 1)) == 15" ]
interview
[]
APPS/1231
def sum_of_digits_of_powers(T: int, numbers: List[int]) -> List[int]: """ The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2. He just started calculating the powers of two. And adding the digits of the results. But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of digits. -----Input----- N : number of inputs N<=100 then N lines with input T<=2000 -----Output----- The output for the corresponding input T -----Example----- Input: 3 5 10 4 Output: 5 7 7 Explanation: 2^5=32 3+2=5 2^10=1024 1+0+2+4=7 2^4=16 1+6=7 """
sum_of_digits_of_powers
def check(candidate): assert candidate(3, [5, 10, 4]) == [5, 7, 7] check(sum_of_digits_of_powers)
[ "assert sum_of_digits_of_powers(3, [5, 10, 4]) == [5, 7, 7]" ]
interview
[]
APPS/1159
def string_game_winner(T: int, test_cases: List[str]) -> List[str]: """ Abhi and his friends (Shanky,Anku and Pandey) love to play with strings. Abhi invented a simple game. He will give a string S to his friends. Shanky and Anku will play the game while Pandey is just a spectator. Shanky will traverse the string from beginning (left to right) while Anku will traverse from last (right to left). Both have to find the first character they encounter during their traversal,that appears only once in the entire string. Winner will be one whose character is alphabetically more superior(has higher ASCII value). When it is not possible to decide the winner by comparing their characters, Pandey will be the winner. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case contains a string S having only lowercase alphabets ( a..z ). -----Output----- For each test case, output a single line containing "SHANKY" if Shanky is the winner or "ANKU" if Anku is the winner or "PANDEY" if the winner is Pandey. Output your answer without quotes. -----Constraints----- - 1 ≤ T ≤ 100 - 1 < |S| ≤ 10^5 -----Example----- Input: 3 google breakraekb aman Output: SHANKY PANDEY ANKU -----Explanation----- Example case 2. Both Shanky and Anku can not find any such character. Hence it is not possible to decide the winner between these two. So Pandey is the winner. """
string_game_winner
def check(candidate): assert candidate(3, ['google', 'breakraekb', 'aman']) == ['SHANKY', 'PANDEY', 'ANKU'] check(string_game_winner)
[ "assert string_game_winner(3, ['google', 'breakraekb', 'aman']) == ['SHANKY', 'PANDEY', 'ANKU']" ]
interview
[]
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
105