Interview Preparation Kit
Interview Preparation Kit
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical
representation:
abc
d
efg
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the
hourglass sum for every hourglass in , then print the maximum hourglass sum.
-9 -9 -9 1 1 1
0 -9 0 432
-9 -9 -9 1 2 3
0 0 8 660
0 0 0 -2 0 0
0 0 1 240
043
1
866
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this
challenge.
Function Description
Complete the function hourglassSum in the editor below. It should return an integer, the maximum
hourglass sum in the array.
Input Format
Constraints
Output Format
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
Explanation
244
2
124
Arrays: Left Rotation
A left rotation operation on an array shifts each of the array's elements unit to the left. For example, if
left rotations are performed on array , then the array would become .
Given an array of integers and a number, , perform left rotations on the array. Return the updated
array to be printed as a single line of space-separated integers.
Function Description
Complete the function rotLeft in the editor below. It should return the resulting array of integers.
An array of integers .
Input Format
The first line contains two space-separated integers and , the size of and the number of left rotations
you must perform.
The second line contains space-separated integers .
Constraints
Output Format
Print a single line of space-separated integers denoting the final state of the array after performing
left rotations.
Sample Input
54
12345
Sample Output
51234
Explanation
When we perform left rotations, the array undergoes the following sequence of changes:
New Year Chaos
It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of
people queued up, and each person wears a sticker indicating their initial position in the queue. Initial
positions increment by from at the front of the line to at the back.
Any person in the queue can bribe the person directly in front of them to swap positions. If two people
swap positions, they still wear the same sticker denoting their original places in line. One person can bribe
at most two others . For example, if and bribes , the queue will look like this:
.
Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took
place to get the queue into its current state!
Function Description
Complete the function minimumBribes in the editor below. It must print an integer representing the
minimum number of bribes necessary, or Too chaotic if the line configuration is not possible.
q: an array of integers
Input Format
Constraints
Subtasks
For score
For score
Output Format
Print an integer denoting the minimum number of bribes needed to get the queue into its final state. Print
Too chaotic if the state is invalid, i.e. it requires a person to have bribed more than people.
Sample Input
2
5
21534
5
25134
Sample Output
3
Too chaotic
Explanation
Test Case 1
Test Case 2
No person can bribe more than two people, so its not possible to achieve the input state.
Minimum Swaps 2
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any
duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps
required to sort the array in ascending order.
Function Description
Complete the function minimumSwaps in the editor below. It must return an integer representing the
minimum number of swaps to sort the array.
Input Format
Constraints
Output Format
Sample Input 0
4
4312
Sample Output 0
Explanation 0
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Sample Input 1
5
23415
Sample Output 1
Explanation 1
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Sample Input 2
7
1352468
Sample Output 2
Explanation 2
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of
the array element between two given indices, inclusive. Once all operations have been performed, return
the maximum value in your array.
For example, the length of your array of zeros . Your list of queries is as follows:
abk
153
487
691
index-> 1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
Function Description
Complete the function arrayManipulation in the editor below. It must return an integer, the maximum
value in the resulting array.
queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and
k.
Input Format
The first line contains two space-separated integers and , the size of the array and the number of
operations.
Each of the next lines contains three space-separated integers , and , the left index, right index
and summand.
Constraints
Output Format
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
Explanation
Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his
ransom note exactly using whole words from the magazine; otherwise, print No .
For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine
has all the right words, but there's a case mismatch. The answer is .
Function Description
Complete the checkMagazine function in the editor below. It must print if the note can be formed
using the magazine, or .
Input Format
The first line contains two space-separated integers, and , the numbers of words in the
and the ..
The second line contains space-separated strings, each .
The third line contains space-separated strings, each .
Constraints
Output Format
Print Yes if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print
No .
Sample Input 0
64
give me one grand today night
give one grand today
Sample Output 0
Yes
Sample Input 1
65
two times three is not four
two times two is four
Sample Output 1
No
Explanation 1
Sample Input 2
74
ive got a lovely bunch of coconuts
ive got some coconuts
Sample Output 2
No
Explanation 2
For example, the words "a", "and", "art" share the common substring . The words "be" and "cat" do not
share a substring.
Function Description
Complete the function twoStrings in the editor below. It should return a string, either YES or NO based
on whether the strings share a common substring.
Input Format
The first line contains a single integer , the number of test cases.
Constraints
Output Format
Sample Input
2
hello
world
hi
world
Sample Output
YES
NO
Explanation
Function Description
Complete the function sherlockAndAnagrams in the editor below. It must return an integer representing
the number of anagrammatic pairs of substrings in .
s: a string .
Input Format
Constraints
Output Format
Sample Input 0
2
abba
abcd
Sample Output 0
4
0
Explanation 0
Sample Input 1
2
ifailuhkqq
kkkk
Sample Output 1
3
10
Explanation 1
For the first query, we have anagram pairs and at positions and
respectively.
Sample Input 2
1
cdcd
Sample Output 2
Explanation 2
Function Description
Complete the countTriplets function in the editor below. It should return the number of triplets forming a
geometric progression for a given as an integer.
Input Format
The first line contains two space-separated integers and , the size of and the common ratio.
The next line contains space-seperated integers .
Constraints
Output Format
Sample Input 0
42
1224
Sample Output 0
Explanation 0
There are triplets in satisfying our criteria, whose indices are and
Sample Input 1
63
1 3 9 9 27 81
Sample Output 1
6
Explanation 1
Sample Input 2
55
1 5 5 25 125
Sample Output 2
Explanation 2
The queries are given in the form of a 2-D array of size where contains the
operation, and contains the data element. For example, you are given array
. The results of each operation are:
Function Description
Complete the solve function in the editor below. It must return an array of integers where each element is
a if there is at least one element value with the queried number of occurrences in the current array, or 0
if there is not.
Input Format
Constraints
All
Output Format
Sample Input 0
8
1 5
1 6
3 2
1 10
1 10
1 6
2 5
3 2
Sample Output 0
0
1
Explanation 0
For the first query of type , there is no integer whose frequency is ( ). So answer is .
For the second query of type , there are two integers in whose frequency is
(integers = and ). So, the answer is .
Sample Input 1
4
3 4
2 1003
1 16
3 1
Sample Output 1
0
1
Explanation 1
For the first query of type , there is no integer of frequency . The answer is .
For the second query of type , there is one integer, of frequency so the answer is .
Sample Input 2
10
13
23
32
14
15
15
14
32
24
32
Sample Output 2
0
1
1
Explanation 2
When the first output query is run, the array is empty. We insert two 's and two 's before the second
output query, so there are two instances of elements occurring twice. We delete a and
run the same query. Now only the instances of satisfy the query.
Sorting: Bubble Sort
Consider the following version of Bubble Sort:
Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once
sorted, print the following three lines:
1. Array is sorted in numSwaps swaps. , where is the number of swaps that took place.
2. First Element: firstElement , where is the first element in the sorted array.
3. Last Element: lastElement , where is the last element in the sorted array.
Hint: To complete this challenge, you must add a variable that keeps a running tally of all swaps that
occur during execution.
For example, given a worst-case but small array to sort: we go through the following steps:
swap a
0 [6,4,1]
1 [4,6,1]
2 [4,1,6]
3 [1,4,6]
Function Description
Complete the function countSwaps in the editor below. It should print the three lines required, then
return.
a: an array of integers .
Input Format
Constraints
Output Format
You must print the following three lines of output:
1. Array is sorted in numSwaps swaps. , where is the number of swaps that took place.
2. First Element: firstElement , where is the first element in the sorted array.
3. Last Element: lastElement , where is the last element in the sorted array.
Sample Input 0
3
123
Sample Output 0
Explanation 0
The array is already sorted, so swaps take place and we print the necessary three lines of output shown
above.
Sample Input 1
3
321
Sample Output 1
Explanation 1
The array is not sorted, and its initial values are: . The following swaps take place:
1.
2.
3.
At this point the array is sorted and we print the necessary three lines of output shown above.
Mark and Toys
Mark and Jane are very happy after having their first kid. Their son loves toys, so Mark wants to buy
some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a
certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For
example, if and Mark has to spend, he can buy items for , or for
units of currency. He would choose the first group of items.
Function Description
Complete the function maximumToys in the editor below. It should return an integer representing the
maximum number of toys Mark can purchase.
Input Format
The first line contains two integers, and , the number of priced toys and the amount Mark has to
spend.
The next line contains space-separated integers
Constraints
Output Format
An integer that denotes the maximum number of toys Mark can buy for his son.
Sample Input
7 50
1 12 5 111 200 1000 10
Sample Output
Explanation
He can buy only toys at most. These toys have the following prices: .
Sorting: Comparator
Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to
sort an array. The Player class is provided in the editor below. It has two fields:
1. : a string.
2. : an integer.
Given an array of Player objects, write a comparator that sorts them in order of decreasing score. If or
more players have the same score, sort those players alphabetically ascending by name. To do this, you
must create a Checker class that implements the Comparator interface, then write an int compare(Player
a, Player b) method implementing the Comparator.compare(T o1, T o2) method. In short, when sorting in
ascending order, a comparator function returns if , if , and if .
Function Description
Declare a Checker class that implements the comparator method as described. It should sort first
descending by score, then ascending by name. The code stub reads the input, creates a list of Player
objects, uses your method to sort the data, and prints it out properly.
Input Format
Locked stub code in the Solution class handles the following input from stdin:
Constraints
Output Format
You are not responsible for printing any output to stdout. Locked stub code in Solution will create a
Checker object, use it to sort the Player array, and print each sorted element.
Sample Input
5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output
aleksa 150
amy 100
david 100
aakansha 75
heraldo 50
Explanation
As you can see, the players are first sorted by decreasing score and then sorted alphabetically by name.
Fraudulent Activity
Notifications
HackerLand National Bank has a simple policy for warning clients about possible fraudulent account
activity. If the amount spent by a client on a particular day is greater than or equal to the client's
median spending for a trailing number of days, they send the client a notification about potential fraud.
The bank doesn't send the client any notifications until they have at least that trailing number of prior
days' transaction data.
Given the number of trailing days and a client's total daily expenditures for a period of days, find and
print the number of times the client will receive a notification over all days.
For example, and . On the first three days, they just collect
spending data. At day , we have trailing expenditures of . The median is and the day's
expenditure is . Because , there will be a notice. The next day, our trailing expenditures
are and the expenditures are . This is less than so no notice will be sent. Over the
period, there was one notice sent.
Note: The median of a list of numbers can be found by arranging all the numbers from smallest to
greatest. If there is an odd number of numbers, the middle one is picked. If there is an even number of
numbers, median is then defined to be the average of the two middle values. (Wikipedia)
Function Description
Complete the function activityNotifications in the editor below. It must return an integer representing the
number of client notifications.
Input Format
The first line contains two space-separated integers and , the number of days of transaction data, and
the number of trailing days' data used to calculate median spending.
The second line contains space-separated non-negative integers where each integer denotes
.
Constraints
Output Format
Print an integer denoting the total number of times the client receives a notification over a period of
days.
Sample Input 0
95
234236845
Sample Output 0
2
Explanation 0
We must determine the total number of the client receives over a period of days.
For the first five days, the customer receives no notifications because the bank has insufficient transaction
data: .
On the sixth day, the bank has days of prior transaction data, , and
dollars. The client spends dollars, which triggers a notification because :
.
On the seventh day, the bank has days of prior transaction data, , and
dollars. The client spends dollars, which triggers a notification because :
.
On the eighth day, the bank has days of prior transaction data, , and
dollars. The client spends dollars, which does not trigger a notification because :
.
On the ninth day, the bank has days of prior transaction data, , and a transaction
median of dollars. The client spends dollars, which does not trigger a notification because
: .
Sample Input 1
54
12344
Sample Output 1
There are days of data required so the first day a notice might go out is day . Our trailing expenditures
are with a median of The client spends which is less than so no notification is
sent.
Merge Sort: Counting
Inversions
In an array, , the elements at indices and (where ) form an inversion if . In
other words, inverted elements and are considered to be "out of order". To correct an
inversion, we can swap adjacent elements.
For example, consider the dataset . It has two inversions: and . To sort the
array, we must perform the following two swaps to correct the inversions:
Given datasets, print the number of inversions that must be swapped to sort each dataset on a new
line.
Function Description
Complete the function countInversions in the editor below. It must return an integer representing the
number of inversions required to sort the array.
Input Format
Constraints
Output Format
For each of the datasets, return the number of inversions that must be swapped to sort the dataset.
Sample Input
2
5
11122
5
21312
Sample Output
0
4
Explanation
We sort the following datasets:
2.
Alice decides on an encryption scheme involving two large strings where encryption is dependent on the
minimum number of character deletions required to make the two strings anagrams. Can you help her
find this number?
Given two strings, and , that may or may not be of the same length, determine the minimum number
of character deletions required to make and anagrams. Any characters can be deleted from either of
the strings.
For example, if and , we can delete from string and from string so that both
remaining strings are and which are anagrams.
Function Description
Complete the makeAnagram function in the editor below. It must return an integer representing the
minimum total characters that must be deleted to make the strings anagrams.
a: a string
b: a string
Input Format
Constraints
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings
anagrams of each other.
Sample Input
cde
abc
Sample Output
Explanation
We delete the following characters from our two strings to turn them into anagrams of each other:
1. Remove d and e from cde to get c .
We must delete characters to make both strings anagrams, so we print on a new line.
Alternating Characters
You are given a string containing characters and only. Your task is to change it into a string such that there are no
matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
For example, given the string , remove an at positions and to make in deletions.
Function Description
Complete the alternatingCharacters function in the editor below. It must return an integer representing the minimum
number of deletions to make the alternating string.
s: a string
Input Format
Constraints
Output Format
For each query, print the minimum number of deletions required on a new line.
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
The characters marked red are the ones that can be deleted so that the string doesn't have matching consecutive
characters.
Sherlock and the
Valid String
Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is
also valid if he can remove just character at index in the string, and the remaining characters will
occur the same number of times. Given a string , determine if it is valid.
Input Format
A single string .
Constraints
Each character
Output Format
Sample Input 0
aabbcd
Sample Output 0
NO
Explanation 0
Given , we would need to remove two characters, both c and d aabb or a and b
abcd , to make it valid. We are limited to removing only one character, so is invalid.
Sample Input 1
aabbccddeefghi
Sample Output 1
NO
Explanation 1
Sample Input 2
abcdefghhgfedecba
Sample Output 2
YES
Explanation 2
All characters occur twice except for which occurs times. We can delete one instance of to have a
valid string.
Special Palindrome
Again
A string is said to be a special palindromic string if either of two conditions is met:
All characters except the middle one are the same, e.g. aadaa .
A special palindromic substring is any substring of a string which meets one of those criteria. Given a
string, determine how many special palindromic substrings can be formed from it.
For example, given the string , we have the following special palindromic substrings:
.
Function Description
Complete the substrCount function in the editor below. It should return an integer representing the
number of special palindromic substrings that can be formed from the given string.
s: a string
Input Format
Constraints
Output Format
Print a single line containing the count of total special palindromic substrings.
Sample Input 0
5
asasd
Sample Output 0
Explanation 0
Sample Input 1
7
abcbaba
Sample Output 1
10
Explanation 1
Sample Input 2
4
aaaa
Sample Output 2
10
Explanation 2
For example, ABCD and ABDC have two children with maximum length 3, ABC and ABD . They can be
formed by eliminating either the D or C from both strings. Note that we will not consider ABCD as a
common child because we can't rearrange characters and ABCD ABDC .
Function Description
Complete the commonChild function in the editor below. It should return the longest string which is a
common child of the input strings.
Input Format
Constraints
Output Format
Print the length of the longest string , such that is a child of both and .
Sample Input
HARRY
SALLY
Sample Output
Explanation
The longest string that can be formed by deleting zero or more characters from and is
, whose length is 2.
Sample Input 1
AA
BB
Sample Output 1
Explanation 1
SHINCHAN
NOHARAAA
Sample Output 2
Explanation 2
The longest string that can be formed between and while maintaining
the order is .
Sample Input 3
ABCDEF
FBDAMN
Sample Output 3
Explanation 3
is the longest child of the given strings.
Minimum Absolute
Difference in an
Array
Consider an array of integers, . We define the absolute difference
between two elements, and (where ), to be the absolute value of .
Given an array of integers, find and print the minimum absolute difference between any two elements in
the array. For example, given the array we can create pairs of numbers:
and . The absolute differences for these pairs are ,
and . The minimum absolute difference is .
Input Format
Constraints
Output Format
Print the minimum absolute difference between any two elements in the array.
Sample Input 0
3
3 -7 0
Sample Output 0
Explanation 0
With integers in our array, we have three possible pairs: , , and . The absolute
values of the differences between these pairs are as follows:
Notice that if we were to switch the order of the numbers in these pairs, the resulting absolute values
would still be the same. The smallest of these possible absolute differences is .
Sample Input 1
10
-59 -36 -13 1 -53 -92 -2 -96 -54 75
Sample Output 1
1
Explanation 1
Sample Input 2
5
1 -3 71 68 17
Sample Output 2
Explanation 2
is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will
decrease by ; if she loses it, her luck balance will increase by .
denotes the contest's importance rating. It's equal to if the contest is important, and it's equal
to if it's unimportant.
If Lena loses no more than important contests, what is the maximum amount of luck she can have after
competing in all the preliminary contests? This value may be negative.
If Lena loses all of the contests, her will be . Since she is allowed to lose important
contests, and there are only important contests. She can lose all three contests to maximize her luck at
. If , she has to win at least of the important contests. She would choose to win the lowest
value important contest worth . Her final luck will be .
Input Format
The first line contains two space-separated integers and , the number of preliminary contests and the
maximum number of important contests Lena can lose.
Each of the next lines contains two space-separated integers, and , the contest's luck balance
and its importance rating.
Constraints
Output Format
Print a single integer denoting the maximum amount of luck Lena can have after all the contests.
Sample Input
63
51
21
11
81
10 0
50
Sample Output
29
Explanation
There are contests. Of these contests, are important and she cannot lose more than of
them. Lena maximizes her luck if she wins the important contest (where ) and loses all of the
other five contests for a total luck balance of .
Greedy Florist
A group of friends want to buy a bouquet of flowers. The florist wants to maximize his number of new
customers and the money he makes. To do this, he decides he'll multiply the price of each flower by the
number of that customer's previously purchased flowers plus . The first flower will be original price,
, the next will be and so on.
Given the size of the group of friends, the number of flowers they want to purchase and the original prices
of the flowers, determine the minimum cost to purchase all of the flowers.
For example, if there are friends that want to buy flowers that cost each will
buy one of the flowers priced at the original price. Having each purchased flower, the first
flower in the list, , will now cost
. The total cost will be
.
Function Description
Complete the getMinimumCost function in the editor below. It should return the minimum cost to
purchase all of the flowers.
Input Format
The first line contains two space-separated integers and , the number of flowers and the number of
friends.
The second line contains space-separated positive integers , the original price of each flower.
Constraints
Output Format
Sample Input 0
33
256
Sample Output 0
13
Explanation 0
There are flowers with costs and people in the group. If each person buys one
flower, the total cost of prices paid is dollars. Thus, we print as our answer.
Sample Input 1
32
256
Sample Output 1
15
Explanation 1
There are flowers with costs and people in the group. We can minimize the total
purchase cost like so:
1. The first person purchases flowers in order of decreasing price; this means they buy the more
expensive flower ( ) first at price dollars and the less expensive flower (
) second at price dollars.
2. The second person buys the most expensive flower at price dollars.
Sample Input 2
53
13579
Sample Output 2
29
Explanation 2
Where:
- max denotes the largest integer in
- min denotes the smallest integer in
As an example, consider the array with a of . Pick any two elements, test
.
Testing for all pairs, the solution provides the minimum unfairness of .
Function Description
Complete the function maxMin in the editor below. It must return the integer representing the minimum
possible unfairness.
Input Format
Constraints
Output Format
Sample Input 0
7
3
10
100
300
200
1000
20
30
Sample Output 0
20
Explanation 0
max(10,20,30) - min(10,20,30) = 30 - 10 = 20
Sample Input 1
10
4
1
2
3
4
10
20
30
40
100
200
Sample Output 1
Explanation 1
max(1,2,3,4) - min(1,2,3,4) = 4 - 1 = 3
Sample Input 2
5
2
1
2
1
2
1
Sample Output 2
Explanation 2
c. denotes any string that's obtained by interspersing the two strings & ,
maintaining the order of characters in both. For example, & , one possible
result of could be , another could be , another could be
and so on.
For example, . We can split it into two strings of . The reverse is and we need to find a
string to shuffle in to get . The middle two characters match our reverse string, leaving the and at
the ends. Our shuffle string needs to be . Lexicographically , so our answer is .
Function Description
Complete the reverseShuffleMerge function in the editor below. It must return the lexicographically
smallest string fitting the criteria.
s: a string
Input Format
Constraints
Output Format
Find and return the string which is the lexicographically smallest valid .
Sample Input 0
eggegg
Sample Output 0
egg
Explanation 0
Sample Input 1
abcdefgabcdefg
Sample Output 1
agfedcb
Explanation 1
Split the string into two strings with like characters: and .
Reverse =
Shuffle can be
Merge to bcdefga
Sample Input 2
aeiouuoiea
Sample Output 2
eaid
Explanation 2
Given the value of and the of each flavor for trips to the Ice Cream Parlor, help Sunny and
Johnny choose two distinct flavors such that they spend their entire pool of money during each visit. ID
numbers are the 1- based index number associated with a . For each trip to the parlor, print the ID
numbers for the two types of ice cream that Sunny and Johnny purchase as two space-separated integers
on a new line. You must print the smaller ID first and the larger ID second.
Note: Two ice creams having unique IDs and may have the same cost (i.e., ).
Function Description
Complete the function whatFlavors in the editor below. It must determine the two flavors they will
purchase and print them as two space-separated integers on a line.
Input Format
The first line contains an integer, , the number of trips to the ice cream parlor.
Constraints
Output Format
Print two space-separated integers denoting the respective indices for the two distinct flavors they choose
to purchase in ascending order. Recall that each ice cream flavor has a unique ID number in the inclusive
range from to .
Sample Input
2
4
5
14532
4
4
2243
Sample Output
14
12
Explanation
Sunny and Johnny make the following two trips to the parlor:
1. The first time, they pool together dollars. There are five flavors available that day and
flavors and have a total cost of .
2. The second time, they pool together dollars. There are four flavors available that day
and flavors and have a total cost of .
Swap Nodes [Algo]
A binary tree is a tree which is characterized by any one of the following properties:
It contains a root node and two subtrees, left subtree and right subtree. These subtrees are also
binary tree.
(For an Inorder traversal, start from the root and keep visiting the left subtree recursively until you reach
the leaf,then you print the node at which you are and then you visit the right subtree.)
If the depth of parent node is d , then the depth of current node wll be d+1 .
Swapping: Swapping subtrees of a node means that if initially node has left subtree L and right subtree
R , then after swapping left subtree will be R and right subtree L .
Depth
1 1 [1]
/\ /\
2 3 -> 3 2 [2]
\ \ \ \
4 5 5 4 [3]
Swap operation: Given a tree and a integer, K , we have to swap the subtrees of all the nodes who are
at depth h , where h ∈ [K, 2K, 3K,...] .
You are given a tree of N nodes where nodes are indexed from [1..N] and it is rooted at 1 . You have to
perform T swap operations on it, and after each swap operation print the inorder traversal of the current
state of the tree.
Input Format
First line of input contains N , number of nodes in tree. Then N lines follow. Here each of ith line (1 <= i
<= N) contains two integers, a b , where a is the index of left child, and b is the index of right child of ith
node. -1 is used to represent null node.
Next line contain an integer, T . Then again T lines follows. Each of these line contains an integer K .
Output Format
For each K , perform swap operation as mentioned above and print the inorder traversal of the current
state of tree.
Constraints
1 <= N <= 1024
1 <= T <= 100
1 <= K <= N
Either a = -1 or 2 <= a <= N
Either b = -1 or 2 <= b <= N
Index of (non-null) child will always be greater than that of parent.
3
23
-1 -1
-1 -1
2
1
1
312
213
5
23
-1 4
-1 5
-1 -1
-1 -1
1
2
42153
11
23
4 -1
5 -1
6 -1
78
-1 9
-1 -1
10 11
-1 -1
-1 -1
-1 -1
2
2
4
2 9 6 4 1 3 7 5 11 8 10
2 6 9 4 1 3 7 5 10 8 11
Explanation
Test Case #00: As node 2 and 3 has no child, swapping will not have any effect on it. We only have to
swap the child nodes of root node.
1 [s] 1 [s] 1
/\ -> / \ -> / \
2 3 [s] 3 2 [s] 2 3
1 1
/\ /\
2 3 [s] -> 2 3
\ \ / /
4 5 4 5
Test Case #02: Here we perform swap operations at the nodes whose depth is either 2 and 4 and then at
nodes whose depth is 4.
1 1 1
/\ /\ /\
/ \ / \ / \
2 3 [s] 2 3 2 3
/ / \ \ \ \
/ / \ \ \ \
4 5 -> 4 5 -> 4 5
/ /\ / /\ / /\
/ / \ / / \ / / \
6 7 8 [s] 6 7 8 [s] 6 7 8
\ /\ / /\ \ /\
\ / \ / / \ \ / \
9 10 11 9 11 10 9 10 11
Pairs
You will be given an array of integers and a target value. Determine the number of pairs of array elements
that have a difference equal to a target value.
For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the
condition: , , and .
Function Description
Complete the pairs function below. It must return an integer representing the number of element pairs
having the required difference.
Input Format
The first line contains two space-separated integers and , the size of and the target value.
The second line contains space-separated integers of the array arr.
Constraints
Output Format
Sample Input
52
15342
Sample Output
Explanation
There are 3 pairs of integers in the set with a difference of 2: [5,3], [4,2] and [3,1] .
Triple sum
Given arrays of different sizes, find the number of distinct triplets where is an element
of , written as , , and , satisfying the criteria: .
Function Description
Complete the triplets function in the editor below. It must return the number of distinct triplets that can be
formed from the given arrays.
Input Format
The first line contains integers , the sizes of the three arrays.
The next lines contain space-separated integers numbering respectively.
Constraints
Output Format
Sample Input 0
3 23
1 35
2 3
1 23
Sample Output 0
Explanation 0
Sample Input 1
3 3 3
1 4 5
2 3 3
1 2 3
Sample Output 1
Explanation 1
The special triplets are
Sample Input 2
4 3 4
1 3 57
5 7 9
7 9 11 13
Sample Output 2
12
Explanation 2
.
Minimum Time
Required
You are planning production for an order. You have a number of machines that each have a fixed number
of days to produce an item. Given that all the machines operate simultaneously, determine the minimum
number of days to produce the required order.
For example, you have to produce items. You have three machines that take
days to produce an item. The following is a schedule of items produced:
Function Description
Complete the minimumTime function in the editor below. It should return an integer representing the
minimum number of days required to complete the order.
machines: an array of integers representing days to produce one item per machine
Input Format
The first line consist of two integers and , the size of and the target production.
The next line contains space-separated integers, .
Constraints
Output Format
Return the minimum time required to produce items considering all machines work simultaneously.
Sample Input 0
25
23
Sample Output 0
Explanation 0
In days can produce items and can produce items. This totals up to .
Sample Input 1
3 10
134
Sample Output 1
Explanation 1
Sample Input 2
3 12
456
Sample Output 2
20
Explanation 2
Given an -element array of integers, , and an integer, , determine the maximum value of the sum of
any of its subarrays modulo . For example, Assume and . The following table lists all
subarrays and their modulus:
sum %2
[1] 1 1
[2] 2 0
[3] 3 1
[1,2] 3 1
[2,3] 5 1
[1,2,3] 6 0
Function Description
Complete the maximumSum function in the editor below. It should return a long integer representing the
maximum value of .
Input Format
The first line contains two space-separated integers and (long) , the length of and the modulo
divisor.
Constraints
Output Format
Sample Input
1
57
33995
Sample Output
Explanation
The subarrays of array and their respective sums modulo are ranked in order of
length and sum in the following list:
1. and
and
2.
3.
4.
5.
Karl just started a level in which he must accumulate candies starting with machines and workers.
In a single pass, he can make candies. After each pass, he can decide whether to spend some of
his candies to buy more machines or hire more workers. Buying a machine or hiring a worker costs
units, and there is no limit to the number of machines he can own or workers he can employ.
Karl wants to minimize the number of passes to make the required number of candies. Determine that
number of passes.
For example, Karl starts with machine and workers. The cost to purchase or hire,
and he needs to accumulate candies. He executes the following strategy:
3. Make candies.
Function Description
Complete the minimumPasses function in the editor below. The function must return a long integer
representing the minimum number of passes required.
Input Format
A single line consisting of four space-separated integers describing the values of , , , and , the
starting number of machines and workers, the cost of a new machine or a new hire, and the the number
of candies Karl must accumulate to complete the level.
Constraints
Output Format
Return a long integer denoting the minimum number of passes required to accumulate at least candies.
Sample Input
3 1 2 12
Sample Output
3
Explanation
3. In the third pass, Karl makes candies. Because this satisfies his goal of making at least
candies, we print the number of passes (i.e., ) as our answer.
Max Array Sum
Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate
the sum of that subset.
Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] 6
[3, 5] 8
Function Description
Complete the function in the editor below. It should return an integer representing the
maximum subset sum for the given array.
Input Format
Constraints
Output Format
Sample Input 0
5
37465
Sample Output 0
13
Explanation 0
Sample Input 1
5
21584
Sample Output 1
11
Explanation 1
Sample Input 2
5
3 5 -7 8 10
Sample Output 2
15
Explanation 2
Given two strings, and , determine if it's possible to make equal to as described. If so, print YES on
a new line. Otherwise, print NO .
Function Description
Input Format
Constraints
Output Format
For each query, print YES on a new line if it's possible to make string equal to string . Otherwise, print
NO .
Sample Input
1
daBcd
ABC
Sample Output
YES
Explanation
We have daBcd and ABC . We perform the following operation:
For example, assume her students' ratings are [4, 6, 4, 5, 6, 2]. She gives the students candy in the
following minimal amounts: [1, 2, 1, 2, 3, 1]. She must buy a minimum of 10 candies.
Function Description
Complete the candies function in the editor below. It must return the minimum number of candies Alice
must buy.
Input Format
Constraints
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input 0
3
1
2
2
Sample Output 0
Explanation 0
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have
different number of candies. Hence optimal distribution will be 1, 2, 1.
Sample Input 1
10
2
4
2
6
1
7
8
9
2
1
Sample Output 1
19
Explanation 1
Sample Input 2
8
2
4
3
5
2
6
4
5
Sample Output 2
12
Explanation 2
For example, if binary number , we compute its decimal value like so:
Meanwhile, in our well-known decimal number system where each digit ranges from to , the value of
some decimal number, , can be expanded in the same way:
Now that we've discussed both systems, let's combine decimal and binary numbers in a new system we
call decibinary! In this number system, each digit ranges from to (like the decimal number system),
but the place value of each digit corresponds to the one in the binary number system! For example, the
decibinary number represents the decimal number because:
Pretty cool system, right? Unfortunately, there's a problem; two different decibinary numbers could
evaluate to the same decimal value! For example, the decibinary number also evaluates to the
decimal value :
This is a major problem because our new number system has no real applications beyond this challenge!
Consider an infinite list of non-negative decibinary numbers that is sorted according to the following rules:
The decibinary numbers are sorted in increasing order of the decimal value that they evaluate to.
Any two decibinary numbers that evaluate to the same decimal value are ordered by increasing
decimal value, meaning the equivalent decibinary values are strictly interpreted and compared as
decimal values and the smaller decimal value is ordered first. For example, and
both evaluate to . We would order before because
.
Input Format
Constraints
Subtasks
Output Format
For each query, print a single integer denoting the the decibinary number in the list. Note that this
must be the actual decibinary number and not its decimal value.
Sample Input 0
5
1
2
3
4
10
Sample Output 0
0
1
2
10
100
Explanation 0
For each , we print the decibinary number on a new line. See the figure in the problem statement.
Sample Input 1
7
8
23
19
16
26
7
6
Sample Output 1
12
23
102
14
111
4
11
Sample Input 2
10
19
25
6
8
20
10
27
24
30
11
Sample Output 2
102
103
11
12
110
100
8
31
32
5
Balanced Brackets
A bracket is considered to be any one of the following characters: ( , ) , { , } , [ , or ] .
Two brackets are considered to be a matched pair if the an opening bracket (i.e., ( , [ , or { ) occurs to the
left of a closing bracket (i.e., ) , ] , or } ) of the exact same type . There are three types of matched pairs
of brackets: [] , {} , and () .
A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For
example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of
square brackets encloses a single, unbalanced opening bracket, ( , and the pair of parentheses encloses a
single, unbalanced closing square bracket, ] .
By this logic, we say a sequence of brackets is balanced if the following conditions are met:
The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched
pair of brackets.
Given strings of brackets, determine whether each sequence of brackets is balanced. If a string is
balanced, return YES . Otherwise, return NO .
Function Description
Complete the function isBalanced in the editor below. It must return a string: YES if the sequence is
balanced or NO if it is not.
s: a string of brackets
Input Format
Constraints
Output Format
Sample Input
3
{[()]}
{[(])}
{{[[(())]]}}
Sample Output
YES
NO
YES
Explanation
1. The string {[()]} meets both criteria for being a balanced string, so we print YES on a new line.
2. The string {[(])} is not balanced because the brackets enclosed by the matched pair { and } are
not balanced: [(]) .
3. The string {{[[(())]]}} meets both criteria for being a balanced string, so we print YES on a new line.
Queues: A Tale of
Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the
oldest elements to be removed from the front and new elements to be added to the rear. This is called a
First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has
been waiting the longest) is always the first one to be removed.
Dequeue: remove the element from the front of the queue and return it.
In this challenge, you must first implement a queue using two stacks. Then process queries, where each
query is one of the following types:
Function Description
Complete the put, pop, and peek methods in the editor below. They must perform the actions as
described above.
Input Format
Each of the next lines contains a single query in the form described in the problem statement above. All
queries start with an integer denoting the query , but only query is followed by an additional space-
separated value, , denoting the value to be enqueued.
Constraints
It is guaranteed that a valid answer always exists for each query of types and .
Output Format
For each query of type , return the value of the element at the front of the fifo queue on a new line.
Sample Input
10
1 42
2
1 14
3
1 28
3
1 60
1 78
2
2
Sample Output
14
14
Explanation
Largest Rectangle
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and
construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be
constructed.
There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given
by . If you join adjacent buildings, they will form a solid rectangle of area
.
For example, the heights array . A rectangle of height and length can be
constructed within the boundaries. The area formed is .
Function Description
Complete the function largestRectangle int the editor below. It should return an integer representing the
largest rectangle that can be formed within the bounds of consecutive buildings.
Input Format
Constraints
Output Format
Sample Input
5
12345
Sample Output
Explanation
For example, given , consider window sizes of through . Windows of size are
. The maximum value of the minimum values of these windows is . Windows of
size are and their minima are . The maximum of these values is
. Continue this process through window size to finally consider the entire array. All of the answers are
.
Function Description
Complete the riddle function in the editor below. It must return an array of integers representing the
maximum minimum value for each window size from to .
Input Format
Constraints
Output Format
Single line containing space-separated integers denoting the output for each window size from to .
Sample Input 0
4
2 6 1 12
Sample Output 0
12 2 1 1
Explanation 0
Here and
Sample Input 1
7
1 2 3 5 1 13 3
Sample Output 1
13 3 2 1 1 1 1
Explanation 1
Here and
Sample Input 2
6
354762
Sample Output 2
764432
Explanation 2
Here and
For example, you are given a grid with sides described as follows:
...
.X.
...
Your starting position so you start in the top left corner. The ending position is
. The path is . It takes moves to get to the goal.
Function Description
Complete the minimumMoves function in the editor. It must print an integer denoting the minimum moves
required to get from the starting position to the goal.
startX: an integer
startY: an integer
goalX: an integer
goalY: an integer
Input Format
The first line contains an integer , the size of the array grid.
Each of the next lines contains a string of length .
The last line contains four space-separated integers,
Constraints
Output Format
Print an integer denoting the minimum number of steps required to move the castle to the goal position.
Sample Input
3
.X.
.X.
...
0002
Sample Output
Explanation
Here is a path that one could follow in order to reach the destination in steps:
.
Poisonous Plants
There are a number of plants in a garden. Each of these plants has been treated with some amount of
pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the
left one, it dies.
You are given the initial values of the pesticide in each of the plants. Print the number of days after which
no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to
their left.
For example, pesticide levels . Using a -indexed array, day plants and die leaving
. On day , plant of the current array dies leaving . As there is no plant with a
higher concentration of pesticide than the one to its left, plants stop dying after day .
Function Description Complete the function poisonousPlants in the editor below. It must return an
integer representing the number of days until plants no longer die from pesticide.
Input Format
Constraints
Output Format
Output an integer equal to the number of days after which no plants die.
Sample Input
7
6 5 8 4 7 10 9
Sample Output
Explanation
nd
After the 2 nd day the plants stop dying.
Roads and Libraries
The Ruler of HackerLand believes that every citizen of the country should have access to a library.
Unfortunately, HackerLand was hit by a tornado that destroyed all of its libraries and obstructed its roads!
As you are the greatest programmer of HackerLand, the ruler wants your help to repair the roads and
build some new libraries efficiently.
HackerLand has cities numbered from to . The cities are connected by bidirectional roads. A
citizen has access to a library if:
They can travel by road from their city to a city containing a library.
The following figure is a sample map of HackerLand where the dotted lines denote obstructed roads:
The cost of repairing any road is dollars, and the cost to build a library in any city is dollars. If in
the above example and , we would build roads at a cost of and libraries
for a cost of . We don't need to rebuild one of the roads in the cycle .
You are given queries, where each query consists of a map of HackerLand and value of and .
For each query, find the minimum cost of making libraries accessible to all the citizens and print it on a
new line.
Function Description
Complete the function roadsAndLibraries in the editor below. It must return the minimal cost of providing
libraries to all, as an integer.
cities: 2D array of integers where each contains two integers representing cities connected
by an obstructed road .
Input Format
The first line contains a single integer , denoting the number of queries.
Constraints
Each road connects two distinct cities.
Output Format
For each query, print an integer denoting the minimum cost of making libraries accessible to all the
citizens on a new line.
Sample Input
2
3 321
1 2
3 1
2 3
6 625
1 3
3 4
2 4
1 2
2 3
5 6
Sample Output
4
12
Explanation
This gives us a total cost of . Note that we don't need to repair the road between cities
and because we repaired the roads connecting them to city .
2. In this scenario it's optimal to build a library in each city because the cost of building a library (
) is less than the cost of repairing a road ( ).
There are cities, so the total cost is .
Find the nearest
clone
In this challenge, there is a connected undirected graph where each of the nodes is a color. Given a color,
find the shortest path connecting any two nodes of that color. Each edge has a weight of . If there is not
a pair or if the color is not found, print .
Each of the nodes is labeled [node]/[color] and is colored appropriately. If we want the shortest path
between color , blue, we see there is a direct path between nodes and . For green, color , we see
the path length from . There is no pair for node having color , red.
Function Description
Complete the findShortest function in the editor below. It should return an integer representing the length
of the shortest path between two nodes of the same color, or if it is not possible.
Input Format
The first line contains two space-separated integers and , the number of nodes and edges in the
graph.
Each of the next lines contains two space-separated integers and , the nodes
connected by an edge.
The next line contains space-seperated integers, , representing the color id of each node from to
.
The last line contains the id of the color to analyze.
Constraints
Output Format
Print the single integer representing the smallest path length or .
Sample Input 0
4 3
1 2
1 3
4 2
1 211
1
Sample Output 0
Explanation 0
In the above image the distance between the closest nodes having color label is .
Sample Input 1
4 3
1 2
1 3
4 2
1 234
2
Sample Output 1
-1
Explanation 1
Sample Input 2
5 4
1 2
1 3
2 4
3 5
1 2332
2
Sample Output 2
3
Explanation 2
BFS: Shortest Reach
in a Graph
Consider an undirected graph consisting of nodes where each node is labeled from to and the edge
between any two nodes is always of length . We define node to be the starting position for a BFS.
Given a graph, determine the distances from the start node to each of its descendants and return the list
in node number order, ascending. If a node is disconnected, it's distance should be .
For example, there are nodes in the graph with a starting node . The list of
, and each has a weight of .
Starting from node and creating a list of distances, for nodes through we have
.
Function Description
Define a Graph class with the required methods to return a list of distances.
Input Format
The first line contains two space-separated integers, and , the number of nodes and the number
of edges.
Each of the next lines contains two space-separated integers, and , describing an edge
connecting node to node .
The last line contains a single integer, , the index of the starting node.
Constraints
Output Format
For each of the queries, print a single line of space-separated integers denoting the shortest
distances to each of the other nodes from starting position . These distances should be listed
sequentially by node number (i.e., ), but should not include node . If some node is
unreachable from , print as the distance to that node.
Sample Input
2
42
1 2
1 3
1
3 1
2 3
2
Sample Output
6 6 -1
-1 6
Explanation
where our start node, , is node . The shortest distances from to the other nodes are one edge to
node , one edge to node , and there is no connection to node .
where our start node, , is node . There is only one edge here, so node is unreachable from node and
node has one edge connecting it to node . We then print node 's distance to nodes and
(respectively) as a single line of space-separated integers: -1 6 .
Note: Recall that the actual length of each edge is , and we print as the distance to any node that's
unreachable from .
DFS: Connected Cell
in a Grid
Consider a matrix where each cell contains either a or a and any cell containing a is called a filled
cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or
diagonally. In the diagram below, the two colored regions show cells connected to the filled cells. Black on
white are not connected.
If one or more filled cells are also connected, they form a region. Note that each cell in a region is
connected to at least one other cell in the region but is not necessarily directly connected to all the other
cells in the region.
Regions:
Given an matrix, find and print the number of cells in the largest region in the matrix.
Function Description
Complete the function maxRegion in the editor below. It must return an integer value, the size of the
largest region.
Input Format
The first line contains an integer, , the number of rows in the matrix, .
The second line contains an integer, , the number of columns in the matrix.
Constraints
Output Format
Print the number of cells in the largest region in the given matrix.
Sample Input
4
4
1 1 0 0
0 1 1 0
0 0 1 0
1 0 0 0
Sample Output
Explanation
The first region has five cells and the second region has one cell. We choose the larger region.
Matrix
The kingdom of Zion has cities connected by bidirectional roads. There is a unique path between any pair
of cities. Morpheus has found out that the machines are planning to destroy the whole kingdom. If two
machines can join forces, the will attack. Neo has to destroy roads connecting cities with machines in
order to stop them from joining forces. There must not be any path connecting two machines.
Each of the roads takes an amount of time to destroy, and only one can be worked on at a time. Given a
list of edges and times, determine the minimum time to stop the attack.
For example, there are cities called . Three of them have machines and are colored red. The
time to destroy is shown next to each road. If we cut the two green roads, there are no paths between
any two machines. The time required is .
Function Description
Complete the function minTime in the editor below. It must return an integer representing the minimum
time to cut off access between the machines.
Input Format
The first line of the input contains two space-separated integers, and , the number of cities and the
number of machines.
Each of the following lines contains three space-separated integers, , and . There
is a bidirectional road connecting and , and to destroy this road it takes units.
Each of the last lines contains an integer, , the label of a city with a machine.
Constraints
Output Format
Return an integer representing the minimum time required to disrupt the connections among all
machines.
Sample Input
53
218
105
245
134
2
4
0
Sample Output
10
Explanation
The machines are located at the cities , and . Neo can destroy the green roads resulting in a time of
. Destroying the road between cities and instead of between and would work, but it's
not minimal.
Tree: Height of a
Binary Tree
The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For
example, the following binary tree is of height :
Function Description
Complete the getHeight or height function in the editor. It must return the height of a binary tree as an
integer.
Note -The Height of binary tree with single node is taken as zero.
Input Format
The first line contains an integer , the number of nodes in the tree.
Next line contains space separated integer where th integer denotes node[i].data.
Note: Node values are inserted into a binary search tree before a reference to the tree's root node is
passed to your function. In a binary search tree, all nodes on the left branch of a node are less than the
node value. All values on the right branch are greater than the node value.
Constraints
Output Format
Your function should return a single integer denoting the height of the binary tree.
Sample Input
Sample Output
Explanation
There are nodes in this path that are connected by edges, meaning our binary tree's .
Binary Search Tree :
Lowest Common
Ancestor
You are given pointer to the root of the binary search tree and two values and . You need to return
the lowest common ancestor (LCA) of and in the binary search tree.
In the diagram above, the lowest common ancestor of the nodes and is the node . Node is the
lowest node which has nodes and as descendants.
Function Description
Complete the function lca in the editor below. It should return a pointer to the lowest common ancestor
node of the two values given.
Input Format
The first line contains an integer, , the number of nodes in the tree.
The second line contains space-separated integers representing values.
The third line contains two space-separated integers, and .
To use the test data, you will have to create the binary search tree yourself. Here on the platform, the
tree will be created for you.
Constraints
Output Format
Return the a pointer to the node that is the lowest common ancestor of and .
Sample Input
and .
Sample Output
[reference to node 4]
Explanation
The value of every node in a node's left subtree is less than the data value of that node.
The value of every node in a node's right subtree is greater than the data value of that node.
For example, the image on the left below is a valid BST. The one on the right fails on several counts:
- All of the numbers on the right branch from the root are not larger than the root.
- All of the numbers on the right branch from node 5 are not larger than 5.
- All of the numbers on the left branch from node 5 are not smaller than 5.
- The data value 1 is repeated.
Given the root node of a binary tree, determine if it is a binary search tree.
Function Description
Complete the function checkBST in the editor below. It must return a boolean denoting whether or not the
binary tree is a binary search tree.
Input Format
You are not responsible for reading any input from stdin. Hidden code stubs will assemble a binary tree
and pass its root node to your function as an argument.
Constraints
Output Format
Your function must return a boolean true if the tree is a binary search tree. Otherwise, it must return
false.
Sample Input
Sample Output
Yes
Explanation
The tree in the diagram satisfies the ordering property for a Binary Search Tree, so we print Yes .
Tree: Huffman
Decoding
Huffman coding assigns variable length codewords to fixed length input characters based on their
frequencies. More frequent characters are assigned shorter codewords and less frequent characters are
assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the
left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only the leaves will contain
a letter and its frequency count. All other nodes will contain a null instead of a character, and the count of
the frequency of all of it and its descendant characters.
For instance, consider the string ABRACADABRA. There are a total of characters in the string. This
number should match the count in the ultimately determined root of the tree. Our frequencies are
and . The two smallest frequencies are for and , both equal to ,
so we'll create a tree with them. The root node will contain the sum of the counts of its descendants, in
this case . The left node will be the first character encountered, , and the right will contain .
Next we have items with a character count of : the tree we just created, the character and the
character . The tree came first, so it will go on the left of our new root node. will go on the right.
Repeat until the tree is complete, then fill in the 's and 's for the edges. The finished graph looks like:
Input characters are only present in the leaves. Internal nodes have a character value of ϕ (NULL). We can
determine that our values for characters are:
A-0
B - 111
C - 1100
D - 1101
R - 10
AB R AC AD AB R A
0 111 10 0 1100 0 1101 0 111 10 0
or
01111001100011010111100
To avoid ambiguity, Huffman encoding is a prefix free encoding technique. No codeword appears as a
prefix of any other codeword.
To decode the encoded string, follow the zeros and ones to a leaf and return the character there.
You are given pointer to the root of the Huffman tree and a binary coded string to decode. You need to
print the decoded string.
Function Description
Complete the function decode_huff in the editor below. It must return the decoded string.
Input Format
There is one line of input containing the plain string, . Background code creates the Huffman tree then
passes the head node and the encoded string to the function.
Constraints
Output Format
Sample Input
s="1001011"
Sample Output
ABACA
Explanation
S="1001011"
Processing the string from left to right.
S[0]='1' : we move to the right child of the root. We encounter a leaf node with value 'A'. We add 'A' to the decoded string.
We move back to the root.
S[3] = '1' : we move to the right child of the root. We encounter a leaf node with value 'A'. We add 'A' to the decoded string.
We move back to the root.
S[6] = '1' : we move to the right child of the root. We encounter a leaf node with value 'A'. We add 'A' to the decoded string.
We move back to the root.
Decoded String = "ABACA"
Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer
value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the
three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he
inserts should be minimal. Determine the minimal amount that a new node can have to allow creation of a
balanced forest. If it's not possible to create a balanced forest, return -1.
For example, you are given node values and $edges = [[1,2],[1,3],[1,4],[4,5]]. It is
the following tree:
The blue node is root, the first number is node number and the second is its value. Cuts can be made
between nodes and and nodes and to have three trees with sums , and . Adding a new
node of to the third tree completes the solution.
Function Description
Complete the balancedForest function in the editor below. It must return an integer representing the
minimum value of that can be added to allow creation of a balanced forest, or if it is not possible.
Input Format
The first line contains an integer, , the number of nodes in the tree.
The second line contains space-separated integers describing the respective values of
, where each denotes the value at node .
Each of the following lines contains two space-separated integers, and , describing
edge connecting nodes and .
Constraints
Output Format
For each query, return the minimum value of the integer . If no such value exists, return instead.
Sample Input
2
5
1 2211
1 2
1 3
3 5
1 4
3
1 35
1 3
1 2
Sample Output
2
-1
Explanation
Greg can add a new node with and create a new edge connecting nodes and . Then
he cuts the edge connecting nodes and and the edge connecting nodes and . We now have a
three-tree balanced forest where each tree has a sum of .
2. In the second query, it's impossible to add a node in such a way that we can split the tree into a
three-tree balanced forest so we return .
Insert a node at a
specific position in a
linked list
This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
You’re given the pointer to the head node of a linked list, an integer to add to the list and the position at
which the integer must be inserted. Create a new node with the given integer, insert this node at the
desired position and return the head node.
A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head
pointer given may be null meaning that the initial list is empty.
As an example, if your list starts as and you want to insert a node at position with
, your new list should be
Function Description Complete the function SinglyLinkedListNode in the editor. It must return a
reference to the head node of your finished list.
position: an integer position to insert the new node, zero based indexing
Input Format
The first line contains an integer , the number of elements in the linked list.
Each of the next lines contains an integer node[i].data.
The last line contains an integer .
Constraints
Output Format
Return a reference to the list head. Locked code prints the list for you.
Sample Input
3
16
13
7
1
2
Sample Output
16 13 1 7
Explanation
The initial linked list is 16 13 7 . We have to insert at the position which currently has in it. The
updated linked list will be 16 13 1 7
Inserting a Node Into
a Sorted Doubly
Linked List
Given a reference to the head of a doubly-linked list and an integer, , create a new
DoublyLinkedListNode object having data value and insert it into a sorted linked list.
2. : An integer denoting the value of the field for the Node you must insert into the list.
The method must insert a new Node into the sorted (in ascending order) doubly-linked list whose data
value is without breaking any of the list's double links or causing it to become unsorted.
Note: Recall that an empty list (i.e., where ) and a list with one element are sorted lists.
Input Format
The first line contains an integer , the number of elements in the linked list.
Each of the next lines contains an integer, the data for each node of the linked list.
The last line contains an integer which needs to be inserted into the sorted doubly-linked list.
Constraints
Output Format
Do not print anything to stdout. Your method must return a reference to the of the same list
that was passed to it as a parameter.
Sample Input
1
4
1
3
4
10
5
Sample Output
1 3 4 5 10
Explanation
You’re given the pointer to the head node of a doubly linked list. Reverse the order of the nodes in the
list. The head node might be NULL to indicate that the list is empty. Change the next and prev pointers
of all the nodes so that the direction of the list is reversed. Return a reference to the head node of the
reversed list.
Function Description
Complete the reverse function in the editor below. It should return a reference to the head of your
reversed list.
Input Format
The first line contains an integer , the number of elements in the linked list.
The next lines contain an integer each denoting an element of the linked list.
Constraints
Output Format
Return a reference to the head of your reversed list. The provided code will print the reverse array as a
one line of space-separated integers for each test case.
Sample Input
1
4
1
2
3
4
Sample Output
4321
Explanation
Given pointers to the head nodes of linked lists that merge together at some point, find the Node where
the two lists merge. It is guaranteed that the two head Nodes will be different, and neither will be NULL.
Complete the int FindMergeNode(Node* headA, Node* headB) method so that it finds and returns the
data value of the Node where the two lists merge.
Input Format
The FindMergeNode(Node*,Node*) method has two parameters, and , which are the non-
null head Nodes of two separate linked lists that are guaranteed to converge.
Constraints
Output Format
Each Node has a data field containing an integer. Return the integer data for the Node where the two lists
merge.
Sample Input
The diagrams below are graphical representations of the lists that input Nodes and are
connected to. Recall that this is a method-only challenge; the method only has initial visibility to those
Nodes and must explore the rest of the Nodes using some algorithm of your own design.
Test Case 0
1
\
2--->3--->NULL
/
1
Test Case 1
1--->2
\
3--->Null
/
1
Sample Output
2
3
Explanation
Test Case 0: As demonstrated in the diagram above, the merge Node's data field contains the integer .
Test Case 1: As demonstrated in the diagram above, the merge Node's data field contains the integer .
Linked Lists: Detect a
Cycle
A linked list is said to contain a cycle if any node is visited more than once while traversing the list.
Complete the function provided in the editor below. It has one parameter: a pointer to a Node object
named that points to the head of a linked list. Your function must return a boolean denoting
whether or not there is a cycle in the list. If there is a cycle, return true; otherwise, return false.
Input Format
Our hidden code checker passes the appropriate argument to your function. You are not responsible for
reading any input from stdin.
Constraints
Output Format
If the list contains a cycle, your function must return true. If the list does not contain a cycle, it must
return false. The binary integer corresponding to the boolean value returned by your function is printed to
stdout by our hidden code checker.
Sample Input
Sample Output
0
1
Explanation
1. The first list has no cycle, so we return false and the hidden code checker prints to stdout.
2. The second list has a cycle, so we return true and the hidden code checker prints to stdout.
Recursion: Fibonacci
Numbers
The Fibonacci Sequence
The Fibonacci sequence appears in nature all around us, in the arrangement of seeds in a sunflower and
the spiral of a nautilus for example.
The Fibonacci sequence begins with and as its first and second
terms. After these first two elements, each subsequent element is equal to the sum of the previous two
elements.
Programmatically:
Function Description
Complete the recursive function in the editor below. It must return the element in the
Fibonacci sequence.
Input Format
Constraints
Output Format
Locked stub code in the editor prints the integer value returned by the function.
Sample Input
Sample Output
Explanation
Given the respective heights for each of the staircases in his house, find and print the number of ways
he can climb each staircase, module on a new line.
For example, there is staircase in the house that is steps high. Davis can step on the
following sequences of steps:
11111
1112
1121
1211
2111
122
221
212
113
131
311
23
32
Function Description
Complete the stepPerms function in the editor below. It should recursively calculate and return the integer
number of ways Davis can climb the staircase, modulo 10000000007.
Input Format
The first line contains a single integer, , the number of staircases in his house.
Each of the following lines contains a single integer, , the height of staircase .
Constraints
Subtasks
Output Format
For each staircase, return the number of ways Davis can climb it as an integer.
Sample Input
3
1
3
7
Sample Output
1
4
44
Explanation
Let's calculate the number of ways of climbing the first two of the Davis' staircases:
1. The first staircase only has step, so there is only one way for him to climb it (i.e., by jumping
step). Thus, we print on a new line.
2. The second staircase has steps and he can climb it in any of the four following ways:
1.
2.
3.
4.
The following shows an example crossword from the input grid and the list of words to fit,
:
Input Output
++++++++++ ++++++++++
+------+++ +POLAND+++
+++-++++++ +++H++++++
+++-++++++ +++A++++++
+++-----++ +++SPAIN++
+++-++-+++ +++A++N+++
++++++-+++ ++++++D+++
++++++-+++ ++++++I+++
++++++-+++ ++++++A+++
++++++++++ ++++++++++
POLAND;LHASA;SPAIN;INDIA
Function Description
Complete the crosswordPuzzle function in the editor below. It should return an array of strings, each
representing a row of the finished puzzle.
Input Format
Constraints
Output Format
Position the words appropriately in the grid, then return your array of strings for printing.
Sample Input 0
+-++++++++
+-++++++++
+-++++++++
+-----++++
+-+++-++++
+-+++-++++
+++++-++++
++------++
+++++-++++
+++++-++++
LONDON;DELHI;ICELAND;ANKARA
Sample Output 0
+L++++++++
+O++++++++
+N++++++++
+DELHI++++
+O+++C++++
+N+++E++++
+++++L++++
++ANKARA++
+++++N++++
+++++D++++
Sample Input 1
+-++++++++
+-++++++++
+-------++
+-++++++++
+-++++++++
+------+++
+-+++-++++
+++++-++++
+++++-++++
++++++++++
AGRA;NORWAY;ENGLAND;GWALIOR
Sample Output 1
+E++++++++
+N++++++++
+GWALIOR++
+L++++++++
+A++++++++
+NORWAY+++
+D+++G++++
+++++R++++
+++++A++++
++++++++++
Sample Input 2
XXXXXX-XXX
XX------XX
XXXXXX-XXX
XXXXXX-XXX
XXX------X
XXXXXX-X-X
XXXXXX-X-X
XXXXXXXX-X
XXXXXXXX-X
XXXXXXXX-X
ICELAND;MEXICO;PANAMA;ALMATY
Sample Output 2
XXXXXXIXXX
XXMEXICOXX
XXXXXXEXXX
XXXXXXLXXX
XXXPANAMAX
XXXXXXNXLX
XXXXXXDXMX
XXXXXXXXAX
XXXXXXXXTX
XXXXXXXXYX
Recursive Digit Sum
We define super digit of an integer using the following rules:
Otherwise, the super digit of is equal to the super digit of the sum of the digits of .
super_digit(9875) 9+8+7+5 = 29
super_digit(29) 2 + 9 = 11
super_digit(11) 1 + 1 = 2
super_digit(2) = 2
You are given two numbers and . The number is created by concatenating the string times.
Continuing the above example where , assume your value . Your initial
(spaces added for clarity).
superDigit(p) = superDigit(9875987598759875)
5+7+8+9+5+7+8+9+5+7+8+9+5+7+8+9 = 116
superDigit(p) = superDigit(116)
1+1+6 = 8
superDigit(p) = superDigit(8)
All of the digits of sum to . The digits of sum to . is only one digit, so it's the super digit.
Function Description
Complete the function superDigit in the editor below. It must return the calculated super digit as an
integer.
Input Format
Constraints
Output Format
Sample Input 0
148 3
Sample Output 0
3
Explanation 0
Here and , so .
super_digit(P) = super_digit(148148148)
= super_digit(1+4+8+1+4+8+1+4+8)
= super_digit(39)
= super_digit(3+9)
= super_digit(12)
= super_digit(1+2)
= super_digit(3)
= 3.
Sample Input 1
9875 4
Sample Output 1
Sample Input 2
123 3
Sample Output 2
Explanation 2
Here and , so .
super_digit(P) = super_digit(123123123)
= super_digit(1+2+3+1+2+3+1+2+3)
= super_digit(18)
= super_digit(1+8)
= super_digit(9)
=9
Flipping bits
You will be given a list of 32 bit unsigned integers. Flip all the bits (1->0 and 0->1) and print the result as
an unsigned integer.
Input Format
The first line of the input contains , the number of test cases.
The next lines each contain an integer to process.
Constraints
Output Format
Output one line per element from the list with the decimal value of the resulting unsigned integer.
Sample Input 0
3
2147483647
1
0
Sample Output 0
2147483648
4294967294
4294967295
Explanation 0
Sample Input 1
2
4
123456
Sample Output 1
4294967291
4294843839
Explanation 1
Sample Input 2
3
0
802743475
35601423
Sample Output 2
4294967295
3492223820
4259365872
Explanation 2
Time Complexity:
Primality
A prime is a natural number greater than that has no positive divisors other than and itself. Given
integers, determine the primality of each integer and print whether it is Prime or Not prime on a new
line.
Note: If possible, try to come up with an primality algorithm, or see what sort of optimizations
you can come up with for an algorithm. Be sure to check out the Editorial after submitting your
code!
Function Description
Complete the primality function in the editor below. It should return Prime if is prime, or Not prime.
Input Format
The first line contains an integer, , denoting the number of integers to check for primality.
Each of the subsequent lines contains an integer, , the number you must test for primality.
Constraints
Output Format
For each integer, print whether is Prime or Not prime on a new line.
Sample Input
3
12
5
7
Sample Output
Not prime
Prime
Prime
Explanation
1. is divisible by numbers other than and itself (i.e.: , , ), so we print Not prime on a new
line.
You will be given queries. After every query, you need to report the size of the largest friend circle (the
largest group of friends) formed after considering that query.
12
34
23
First, and shake hands, forming a circle of . Next, and do the same. Now there are two groups of
friends. When and become friends in the next query, both groups of friends are added together to
make a circle of friends. We would print
2
2
4
Function Description
Complete the function maxCircle in the editor below. It must return an array of integers representing the
size of the maximum circle of friends after each query.
queries: an array of integer arrays, each with two elements indicating a new friendship
Input Format
You need to complete the function, which takes 2-D integer array of size . After each
query, person and become friends.
Constraints
for
Output Format
Return an integer array of size , whose value at index is the size of largest group present after
processing till query.
Sample Input 0
2
12
13
Sample Output 0
2
3
Explanation 0
In the first query, and shake hands. So, the size of largest group of friends is (as no other friendships
exist).
After the second query, , and all become friends, as shakes hand with , also become friends
with as he was already a friend of .
Sample Input 1
4
1000000000 23
11 3778
7 47
11 1000000000
Sample Output 1
2
2
2
4
Explanation 1
After first query, person and person become friends. So, the largest group size is .
After the second query, person and person become friends. So, the largest group size is still .
After the third query, person and person become friends. Answer is still .
After the last query, person and person become friends, which means , ,
and all become friends. Hence, the answer now increased to .
Sample Input 2
6
1 2
3 4
1 3
5 7
5 6
7 4
Sample Output 2
2
2
4
4
4
7
Explanation 2
1 [1,2]
2 [1,2],[3,4]
3 [1,2,3,4]
4 [1,2,3,4],[5,7]
5 [1,2,3,4],[5,7,6]
6 [1,2,3,4,5,6,7]
Maximum Xor
You are given an array of elements. A list of integers, is given as an input, find the
maximum value of \text{each} arr[i] 0 \le i < n \oplus$ represents xor of two
elements.
Note that there are multiple test cases in one input file.
For example:
Function Description
Complete the maxXor function in the editor below. It must return an array of integers, each representing
the maximum xor value for each element against all elements of .
Input Format
Constraints
Output Format
The output should contain lines with each line representing output for the corresponding input of the
testcase.
Sample Input 0
3
012
3
3
7
2
Sample Output 0
3
7
3
Explanation 0
Sample Input 1
5
51743
2
2
0
Sample Output 1
7
7
Explanation 1
Sample Input 2
4
1357
2
17
6
Sample Output 2
22
7
Explanation 2