You are on page 1of 132

2D Array - DS

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.

For example, given the 2D array:

-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

We calculate the following hourglass values:

-63, -34, -9, 12,


-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18

Our highest hourglass value is from the hourglass:

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.

hourglassSum has the following parameter(s):

arr: an array of integers

Input Format

Each of the lines of inputs contains space-separated integers .

Constraints
Output Format

Print the largest (maximum) hourglass sum found in .

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

contains the following hourglasses:

111 110 100 000


1 0 0 0
111 110 100 000

010 100 000 000


1 1 0 0
002 024 244 440

111 110 100 000


0 2 4 4
000 002 020 200

002 024 244 440


0 0 2 0
001 012 124 240

The hourglass with the maximum sum ( ) is:

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.

rotLeft has the following parameter(s):

An array of integers .

An integer , the number of rotations.

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.

minimumBribes has the following parameter(s):

q: an array of integers

Input Format

The first line contains an integer , the number of test cases.

Each of the next pairs of lines are as follows:


- The first line contains an integer , the number of people in the queue
- The second line has space-separated integers describing the final state of the queue.

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

The initial state:

After person moves one position ahead by bribing person :

Now person moves another position ahead by bribing person :

And person moves one position ahead by bribing person :

So the final state is after three bribing operations.

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.

For example, given the array we perform the following steps:

i arr swap (indices)


0 [7, 1, 3, 2, 4, 5, 6] swap (0,3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6)
5 [1, 2, 3, 4, 5, 6, 7]

It took swaps to sort the array.

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.

minimumSwaps has the following parameter(s):

arr: an unordered array of integers

Input Format

The first line contains an integer, , the size of .


The second line contains space-separated integers .

Constraints

Output Format

Return the minimum number of swaps to sort the given array.

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

Add the values of between the indices and inclusive:

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]

The largest value is after all operations are performed.

Function Description

Complete the function arrayManipulation in the editor below. It must return an integer, the maximum
value in the resulting array.

arrayManipulation has the following parameters:

n - the number of elements in your 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

Return the integer maximum value in the finished array.

Sample Input

5 3
1 2 100
2 5 100
3 4 100
Sample Output

200

Explanation

After the first update list will be 100 100 0 0 0 .


After the second update list will be 100 200 100 100 100 .
After the third update list will be 100 200 200 200 100 .
The required answer will be .
Hash Tables: Ransom
Note
Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him
through his handwriting. He found a magazine and wants to know if he can cut out whole words from it
and use them to create an untraceable replica of his ransom note. The words in his note are case-
sensitive and he must use only whole words available in the magazine. He cannot use substrings or
concatenation to create the words he needs.

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 .

checkMagazine has the following parameters:

magazine: an array of strings, each a word in the magazine

note : an array of strings, each a word in the ransom note

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

Each word consists of English alphabetic letters (i.e., to and to ).

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

'two' only occurs once in the magazine.

Sample Input 2

74
ive got a lovely bunch of coconuts
ive got some coconuts

Sample Output 2

No

Explanation 2

Harold's magazine is missing the word .


Two Strings
Given two strings, determine if they share a common substring. A substring may be as small as one
character.

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.

twoStrings has the following parameter(s):

s1, s2 : two strings to analyze .

Input Format

The first line contains a single integer , the number of test cases.

The following pairs of lines are as follows:

The first line contains string .

The second line contains string .

Constraints

and consist of characters in the range ascii[a-z].

Output Format

For each pair of strings, return YES or NO .

Sample Input

2
hello
world
hi
world

Sample Output

YES
NO

Explanation

We have pairs to check:

1. , . The substrings and are common to both strings.

2. , . and share no common substrings.


Sherlock and
Anagrams
Two strings are anagrams of each other if the letters of one string can be rearranged to form the other
string. Given a string, find the number of pairs of substrings of the string which are anagrams of each
other.

For example , the list of all anagrammatic pairs is at positions


respectively.

Function Description

Complete the function sherlockAndAnagrams in the editor below. It must return an integer representing
the number of anagrammatic pairs of substrings in .

sherlockAndAnagrams has the following parameter(s):

s: a string .

Input Format

The first line contains an integer , the number of queries.


Each of the next lines contains a string to analyze.

Constraints

String contains only lowercase letters ascii[a-z].

Output Format

For each query, return the number of unordered anagrammatic pairs.

Sample Input 0

2
abba
abcd

Sample Output 0

4
0

Explanation 0

The list of all anagrammatic pairs is and at positions


and respectively.

No anagrammatic pairs exist in the second query as no character repeats.

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.

For the second query:


There are 6 anagrams of the form at positions and
.
There are 3 anagrams of the form at positions and .
There is 1 anagram of the form at position .

Sample Input 2

1
cdcd

Sample Output 2

Explanation 2

There are two anagrammatic pairs of length : and .


There are three anagrammatic pairs of length : at positions
respectively.
Count Triplets
You are given an array and you need to find number of tripets of indices such that the elements
at those indices are in geometric progression for a given common ratio and .

For example, . If , we have and at indices and


.

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.

countTriplets has the following parameter(s):

arr: an array of integers

r: an integer, the common ratio

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

Return the count of triplets that form a geometric progression.

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

The triplets satisfying are index , , , , and .

Sample Input 2

55
1 5 5 25 125

Sample Output 2

Explanation 2

The triplets satisfying are index , , , .


Frequency Queries
You are given queries. Each query is of the form two integers described below:
- : Insert x in your data structure.
- : Delete one occurence of y from your data structure, if present.
- : Check if any integer is present whose frequency is exactly . If yes, print 1 else 0.

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:

Operation Array Output


(1,1) [1]
(2,2) [1]
(3,2) 0
(1,1) [1,1]
(1,1) [1,1,1]
(2,1) [1,1]
(3,2) 1

Return an array with the output: .

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.

solve has the following parameter(s):

queries: a 2-d array of integers

Input Format

The first line contains of an integer , the number of queries.


Each of the next lines contains two integers denoting the 2-d array .

Constraints

All

Output Format

Return an integer array consisting of all the outputs of queries of type .

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:

for (int i = 0; i < n; i++) {

for (int j = 0; j < n - 1; j++) {


// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}

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]

It took swaps to sort the array. Output would be

Array is sorted in 3 swaps.


First Element: 1
Last Element: 6

Function Description

Complete the function countSwaps in the editor below. It should print the three lines required, then
return.

countSwaps has the following parameter(s):

a: an array of integers .

Input Format

The first line contains an integer, , the size of the array .


The second line contains space-separated integers .

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

Array is sorted in 0 swaps.


First Element: 1
Last Element: 3

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

Array is sorted in 3 swaps.


First Element: 1
Last Element: 3

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.

maximumToys has the following parameter(s):

prices: an array of integers representing toy prices

k: an integer, Mark's budget

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

A toy can't be bought multiple times.

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 .

For example, given Player objects with values of


, we want to sort the list as
.

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:

The first line contains an integer, , the number of players.


Each of the next lines contains a player's respective and , a string and an integer.

Constraints

Two or more players can have the same name.

Player names consist of lowercase English alphabetic letters.

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.

activityNotifications has the following parameter(s):

expenditure: an array of integers representing daily expenditures

d: an integer, the lookback days for median spending

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.

countInversions has the following parameter(s):

arr: an array of integers to sort .

Input Format

The first line contains an integer, , the number of datasets.

Each of the next pairs of lines is as follows:

1. The first line contains an integer, , the number of elements in .

2. The second line contains space-separated integers, .

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:

1. is already sorted, so there are no inversions for us to correct. Thus, we print on


a new line.

2.

We performed a total of swaps to correct inversions.


Strings: Making
Anagrams
Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be
anagrams of each other if the first string's letters can be rearranged to form the second string. In other
words, both strings must contain the same exact letters in the same exact frequency For example, bacdc
and dcbac are anagrams, but bacdc and dcbad are not.

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.

makeAnagram has the following parameter(s):

a: a string

b: a string

Input Format

The first line contains a single string, .


The second line contains a single string, .

Constraints

The strings and consist of lowercase English alphabetic letters ascii[a-z].

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 .

2. Remove a and b from abc 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.

Your task is to find the minimum number of required deletions.

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.

alternatingCharacters has the following parameter(s):

s: a string

Input Format

The first line contains an integer , the number of queries.


The next lines each contain a string .

Constraints

Each string will consist only of characters and

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.

For example, if , it is a valid string because frequencies are . So is


because we can remove one and have of each character in the remaining string. If
however, the string is not valid as we can only remove occurrence of . That would leave character
frequencies of .

Input Format

A single string .

Constraints

Each character

Output Format

Print YES if string is valid, otherwise, print NO .

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

Frequency counts for the letters are as follows:

{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2, 'f': 1, 'g': 1, 'h': 1, 'i': 1}

There are two ways to make the valid string:

Remove characters with a frequency of : .


Remove characters of frequency : .

Neither of these is an option.

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 of the characters are the same, e.g. aaa .

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.

substrCount has the following parameter(s):

n: an integer, the length of string s

s: a string

Input Format

The first line contains an integer, , the length of .


The second line contains the string .

Constraints

Each character of the string is a lowercase alphabet, .

Output Format

Print a single line containing the count of total special palindromic substrings.

Sample Input 0

5
asasd

Sample Output 0

Explanation 0

The special palindromic substrings of are

Sample Input 1

7
abcbaba

Sample Output 1
10

Explanation 1

The special palindromic substrings of are

Sample Input 2

4
aaaa

Sample Output 2

10

Explanation 2

The special palindromic substrings of are


Common Child
A string is said to be a child of a another string if it can be formed by deleting 0 or more characters from
the other string. Given two strings of equal length, what's the longest string that can be constructed such
that it is a child of both?

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.

commonChild has the following parameter(s):

s1, s2 : two equal length strings

Input Format

There is one line with two space-separated strings, and .

Constraints

All characters are upper case in the range ascii[A-Z].

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

and have no characters in common and hence the output is 0.


Sample Input 2

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

The first line contains a single integer , the size of .


The second line contains space-separated integers .

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

The smallest absolute difference is .

Sample Input 2

5
1 -3 71 68 17

Sample Output 2

Explanation 2

The minimum absolute difference is .


Luck Balance
Lena is preparing for an important coding competition that is preceded by a number of sequential
preliminary contests. She believes in "saving luck", and wants to check her theory. Each contest is
described by two integers, and :

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.

For example, and:

Contest L[i] T[i]


1 51
2 11
3 40

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.

getMinimumCost has the following parameter(s):

c: an array of integers representing the original price of each flower

k: an integer, the number of friends

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

Print the minimum cost to buy all flowers.

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.

We then print the sum of these purchases, which is , as our answer.

Sample Input 2

53
13579

Sample Output 2

29

Explanation 2

The friends buy flowers for , and , and for a cost of .


Max Min
You will be given a list of integers, , and a single integer . You must create an array of length from
elements of such that its unfairness is minimized. Call that array . Unfairness of an array is
calculated as

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 .

Note: Integers in may not be unique.

Function Description

Complete the function maxMin in the editor below. It must return the integer representing the minimum
possible unfairness.

maxMin has the following parameter(s):

k: an integer, the length of the subarrays

arr: an array of integers

Input Format

The first line contains an integer , the number of elements in array .


The second line contains an integer .
Each of the next lines contains an integer where .

Constraints

Output Format

An integer that denotes the minimum possible value of unfairness.

Sample Input 0

7
3
10
100
300
200
1000
20
30

Sample Output 0

20
Explanation 0

Here ; selecting the integers , unfairness equals

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

Here ; selecting the integers , unfairness equals

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

Here . or give the minimum unfairness of .


Reverse Shuffle
Merge
Given a string, , we define some operations on the string as follows:

a. denotes the string obtained by reversing string . Example:

b. denotes any string that's a permutation of string . Example:

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.

Given a string such that for some string , find the


lexicographically smallest .

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.

reverseShuffleMerge has the following parameter(s):

s: a string

Input Format

A single line containing the string .

Constraints

contains only lower-case English letters, ascii[a-z]

Output Format

Find and return the string which is the lexicographically smallest valid .

Sample Input 0

eggegg

Sample Output 0

egg

Explanation 0

Split "eggegg" into strings of like character counts: "egg", "egg"


reverse("egg") = "gge"
shuffle("egg") can be "egg"
"eggegg" belongs to the merge of ("gge", "egg")

The merge is: gge .

'egg' < 'gge'

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

Split the string into groups of like characters:


Reverse =
These merge to uoiea
Hash Tables: Ice
Cream Parlor
Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they pool their money to buy ice cream.
On any given day, the parlor offers a line of flavors. Each flavor has a cost associated with it.

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.

For example, there are flavors having . Together they have to


spend. They would purchase flavor ID's and for a cost of . Use based indexing for your
response.

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.

whatFlavors has the following parameter(s):

cost: an array of integers representing price for a flavor

money: an integer representing the amount of money they have to spend

Input Format

The first line contains an integer, , the number of trips to the ice cream parlor.

Each of the next sets of lines is as follows:

The first line contains .

The second line contains an integer, , the size of the array .

The third line contains space-separated integers denoting the .

Constraints

There will always be a unique solution.

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 can be an empty (null).

It contains a root node and two subtrees, left subtree and right subtree. These subtrees are also
binary tree.

Inorder traversal is performed as

1. Traverse the left subtree.

2. Visit root (print it).

3. Traverse the right subtree.

(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.)

We define depth of a node as follow:

Root node is at depth 1.

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 .

Eg. In the following tree, we swap children of node 1 .

Depth
1 1 [1]
/\ /\
2 3 -> 3 2 [2]
\ \ \ \
4 5 5 4 [3]

Inorder traversal of left tree is 2 4 1 3 5 and of right tree is 3 5 1 2 4 .

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.

Sample Input #00

3
23
-1 -1
-1 -1
2
1
1

Sample Output #00

312
213

Sample Input #01

5
23
-1 4
-1 5
-1 -1
-1 -1
1
2

Sample Output #01

42153

Sample Input #02

11
23
4 -1
5 -1
6 -1
78
-1 9
-1 -1
10 11
-1 -1
-1 -1
-1 -1
2
2
4

Sample Output #02

2 9 6 4 1 3 7 5 11 8 10
2 6 9 4 1 3 7 5 10 8 11

Explanation

** [s] represents swap operation is done at this depth.

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

Test Case #01: Swapping child nodes of node 2 and 3 we get

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.

pairs has the following parameter(s):

k: an integer, the target difference

arr: an array of integers

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

each integer will be unique

Output Format

An integer representing the number of pairs of integers whose difference is .

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: .

For example, given and , we find four distinct triplets:


.

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.

triplets has the following parameter(s):

a, b, c : three arrays of integers .

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

Print an integer representing the number of distinct triplets.

Sample Input 0

3 23
1 35
2 3
1 23

Sample Output 0

Explanation 0

The special triplets are .

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

The special triplets are

.
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:

Day Production Count


2 2 2
3 1 3
4 2 5
6 3 8
8 2 10

It takes days to produce items using these machines.

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.

minimumTime has the following parameter(s):

machines: an array of integers representing days to produce one item per machine

goal: an integer, the number of items required to complete the order

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

In minutes, can produce items, can produce items and can


produce item, which totals up to .

Sample Input 2

3 12
456

Sample Output 2

20

Explanation 2

In days can produce items, can produce , and can produce


.
Maximum Subarray
Sum
We define the following:

A subarray of array of length is a contiguous segment from through where


.

The sum of an array is the sum of its elements.

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

The maximum modulus is .

Function Description

Complete the maximumSum function in the editor below. It should return a long integer representing the
maximum value of .

maximumSum has the following parameter(s):

a: an array of long integers, the array to analyze

m : a long integer, the modulo divisor

Input Format

The first line contains an integer , the number of queries to perform.

The next pairs of lines are as follows:

The first line contains two space-separated integers and (long) , the length of and the modulo
divisor.

The second line contains space-separated long integers .

Constraints

the sum of over all test cases

Output Format

For each query, return the maximum value of as a long integer.

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.

The maximum value for for any subarray is .


Making Candies
Karl loves playing games on social networking sites. His current favorite is CandyMaker, where the goal is
to make candies.

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:

1. Make candies. Purchase two machines.

2. Make candies. Purchase machines and hire workers.

3. Make candies.

It took passes to make enough 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.

minimumPasses has the following parameter(s):

m : long integer, the starting number of machines

w: long integer, the starting number of workers

p: long integer, the cost of a new hire or a new machine

n: long integer, the number of candies to produce

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

Karl makes three passes:

1. In the first pass, he makes candies. He then spends of them hiring


another worker, so and he has one candy left over.

2. In the second pass, he makes candies. He spends of them on another machine


and another worker, so and and he has candies left over.

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.

For example, given an array we have the following possible subsets:

Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] 6
[3, 5] 8

Our maximum subset sum is .

Function Description

Complete the function in the editor below. It should return an integer representing the
maximum subset sum for the given array.

maxSubsetSum has the following parameter(s):

arr: an array of integers

Input Format

The first line contains an integer, .


The second line contains space-separated integers .

Constraints

Output Format

Return the maximum sum described in the statement.

Sample Input 0

5
37465

Sample Output 0

13

Explanation 0

Our possible subsets are and . The largest subset sum is


from subset

Sample Input 1

5
21584
Sample Output 1

11

Explanation 1

Our subsets are and . The maximum subset sum is from


the first subset listed.

Sample Input 2

5
3 5 -7 8 10

Sample Output 2

15

Explanation 2

Our subsets are and . The maximum subset sum is


from the fifth subset listed.
Abbreviation
You can perform the following operations on the string, :

1. Capitalize zero or more of 's lowercase letters.

2. Delete all of the remaining lowercase letters in .

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 .

For example, given and , in we can convert and delete to match . If


and , matching is not possible because letters may only be capitalized or
discarded, not changed.

Function Description

Complete the function in the editor below. It must return either or .

abbreviation has the following parameter(s):

a: the string to modify

b: the string to match

Input Format

The first line contains a single integer , the number of queries.

Each of the next pairs of lines is as follows:


- The first line of each query contains a single string, .
- The second line of each query contains a single string, .

Constraints

String consists only of uppercase and lowercase English letters, ascii[A-Za-z].

String consists only of uppercase English letters, ascii[A-Z].

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:

1. Capitalize the letters a and c in so that dABCd .

2. Delete all the remaining lowercase letters in so that ABC .

Because we were able to successfully convert to , we print YES on a new line.


Candies
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the
children sit in a line and each of them has a rating score according to his or her performance in the class.
Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with
the higher rating must get more candies. Alice wants to minimize the total number of candies she must
buy.

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.

candies has the following parameter(s):

n: an integer, the number of children in the class

arr: an array of integers representing the ratings of each student

Input Format

The first line contains an integer, , the size of .


Each of the next lines contains an integer indicating the rating of the student at position .

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

Optimal distribution will be

Sample Input 2

8
2
4
3
5
2
6
4
5

Sample Output 2

12

Explanation 2

Optimal distribution will be .


Decibinary Numbers
Let's talk about binary numbers . We have an -digit binary number, , and we denote the digit at index
(zero-indexed from right to left) to be . We can find the decimal value of using the following formula:

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
.

Here is a list of first few decibinary numbers properly ordered:


You will be given queries in the form of an integer, . For each , find and print the the decibinary
number in the list on a new line.

Input Format

The first line contains an integer, , denoting the number of queries.


Each line of the subsequent lines contains a single integer, , describing a query.

Constraints

Subtasks

for of the maximum score

for of the maximum score

for of the maximum score

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:

It contains no unmatched brackets.

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.

isBalanced has the following parameter(s):

s: a string of brackets

Input Format

The first line contains a single integer , the number of strings.


Each of the next lines contains a single string , a sequence of brackets.

Constraints

, where is the length of the sequence.

All chracters in the sequences ∈ { {, }, (, ), [, ] }.

Output Format

For each string, return YES or NO .

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.

A basic queue has the following operations:

Enqueue: add a new element to the end of the queue.

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:

1. 1 x : Enqueue element into the end of the queue.

2. 2 : Dequeue the element at the front of the queue.

3. 3 : Print the element at the front of the queue.

For example, a series of queries might be as follows:

Function Description

Complete the put, pop, and peek methods in the editor below. They must perform the actions as
described above.

Input Format

The first line contains a single integer, , the number of queries.

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.

largestRectangle has the following parameter(s):

h: an array of integers representing building heights

Input Format

The first line contains , the number of buildings.


The second line contains space-separated integers, each representing the height of a building.

Constraints

Output Format

Print a long integer representing the maximum area of rectangle formed.

Sample Input

5
12345

Sample Output

Explanation

An illustration of the test case follows.


1 2 3 4 5
Min Max Riddle
Given an integer array of size , find the maximum of the minimum(s) of every window size in the array.
The window size varies from to .

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 .

riddle has the following parameter(s):

arr: an array of integers

Input Format

The first line contains a single integer, , the size of .


The second line contains space-separated integers, each an .

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

window sizewindow1window2window3window4maximum of all windows


1 2 6 1 12 12
2 2 1 1 2
3 1 1 1
4 1 1

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

win sizew_1w_2w_3w_4w_5w_6w_7maximum of all windows


1 1 2 3 5 1 13 3 13
2 1 2 3 1 1 3 3
3 1 2 1 1 1 2
4 1 1 1 1 1
5 1 1 1 1
6 1 1 1
7 1 1

Sample Input 2

6
354762

Sample Output 2

764432

Explanation 2

Here and

win sizew_1w_2w_3w_4w_5w_6maximum of all windows


1 3 5 4 7 6 2 7
2 3 4 4 6 2 6
3 3 4 4 2 4
4 3 4 2 4
5 3 2 3
6 2 2
Castle on the Grid
You are given a square grid with some cells open ( .) and some blocked (X). Your playing piece can move
along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and an
end position, determine the number of moves it will take to get to the end position.

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.

minimumMoves has the following parameter(s):

grid: an array of strings representing the rows of the grid

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.

poisonousPlants has the following parameter(s):

p: an array of integers representing pesticide levels in each plant

Input Format

The first line contains an integer , the size of the array .


The next line contains space-separated integers .

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

Initially all plants are alive.

Plants = {(6,1), (5,2), (8,3), (4,4), (7,5), (10,6), (9,7)}

Plants[k] = (i,j) => j th plant has pesticide amount = i.

After the 1 st day, 4 plants remain as plants 3, 5, and 6 die.

Plants = {(6,1), (5,2), (4,4), (9,7)}

After the 2 nd day, 3 plants survive as plant 7 dies.

Plants = {(6,1), (5,2), (4,4)}

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:

Their city contains a library.

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.

roadsAndLibraries has the following parameters:

n: integer, the number of cities

c_lib: integer, the cost to build a library

c_road: integer, the cost to repair a road

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.

The subsequent lines describe each query in the following format:


- The first line contains four space-separated integers describing the respective values of , , and
, the number of cities, number of roads, cost of a library and cost of a road.
- Each of the next lines contains two space-separated integers, and , describing a bidirectional
road connecting cities and .

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

We perform the following queries:

1. HackerLand contains cities connected by bidirectional roads. The price of building a


library is and the price for repairing a road is .

The cheapest way to make libraries accessible to all is to:

Build a library in city at a cost of .

Repair the road between cities and at a cost of .

Repair the road between cities and at a cost of .

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 .

For example, given , and edges and and


colors for each node are we can draw the following graph:

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.

findShortest has the following parameter(s):

g_nodes: an integer, the number of nodes

g_from: an array of integers, the start nodes for each edge

g_to: an array of integers, the end nodes for each edge

ids: an array of integers, the color id per node

val: an integer, the id of the color to match

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.

Note: The nodes are indexed from to .

Constraints

The graph is acyclic.

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 an integer, , the number of queries.

Each of the following sets of lines is as follows:

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

We perform the following two queries:

1. The given graph can be represented as:

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 .

2. The given graph can be represented as:

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.

Cells adjacent to filled cells:

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.

maxRegion has the following parameter(s):

grid: a two dimensional array of integers

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.

Each of the following lines contains a row of space-separated integers, .

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 diagram below depicts two regions of the matrix:

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.

minTime has the following parameter(s):

roads: a two-dimensional array of integers, each where cities are


connected by a road that takes to destroy

machines: an array of integers representing cities with 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.

getHeight or height has the following parameter(s):

root: a reference to the root of a binary tree.

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

The longest root-to-leaf path is shown below:

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.

lca has the following parameters:


- root: a pointer to the root node of a binary search tree
- v1: a node.data value
- v2: a node.data value

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

The tree will contain nodes with data equal to and .

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

LCA of and is , the root in this case.


Return a pointer to the node.
Trees: Is This a
Binary Search Tree?
For the purposes of this challenge, we define a binary search tree to be a binary tree with the following
properties:

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.

The value of every node is distinct.

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.

checkBST has the following parameter(s):

root: a reference to the root node of a tree to test

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

Our Huffman encoded string is:

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.

decode_huff has the following parameters:

root: a reference to the root node of the Huffman tree

s: a Huffman encoded 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

Output the decoded string on a single line.

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[1]='0' : we move to the left child.


S[2]='0' : we move to the left child. We encounter a leaf node with value 'B'. We add 'B' 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[4]='0' : we move to the left child.


S[5]='1' : we move to the right child. We encounter a leaf node with value C'. We add 'C' 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.

balancedForest has the following parameter(s):

c: an array of integers, the data values for each node

edges: an array of 2 element arrays, the node pairs per edge

Input Format

The first line contains a single integer, , the number of queries.

Each of the following sets of lines is as follows:

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

Each query forms a valid undirected tree.


Subtasks

For of the maximum score:

For of the maximum score:

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

We perform the following two queries:

1. The tree initially looks like this:

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.

SinglyLinkedListNode has the following parameters:

head: a SinglyLinkedListNode pointer to the head of the list

data: an integer value to insert as data in your new node

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

, where is the element of the linked list.

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.

Complete the DoublyLinkedListNode SortedInsert(DoublyLinkedListNode head, int data) method in the


editor below. It has two parameters:

1. : A reference to the head of a doubly-linked list of Node objects.

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 test cases.

Each of the test case is in the following 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.

The ouput is handled by the code in the editor and is as follows:


For each test case, print the elements of the sorted doubly-linked list separated by spaces on a new line.

Sample Input

1
4
1
3
4
10
5

Sample Output

1 3 4 5 10
Explanation

The initial doubly linked list is: .

The doubly linked list after insertion is:


Reverse a doubly
linked list
This challenge is part of a tutorial track by MyCodeSchool

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.

reverse has the following parameter(s):

head: a reference to the head of a DoublyLinkedList

Input Format

The first line contains an integer , the number of test cases.

Each test case is of the following 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

The initial doubly linked list is:

The reversed doubly linked list is:


Find Merge Point of
Two Lists
This challenge is part of a tutorial track by MyCodeSchool

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.

In the diagram below, the two lists converge at Node x :

[List #1] a--->b--->c


\
x--->y--->z--->NULL
/
[List #2] p--->q

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

Do not read any input from stdin/console.

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

The lists will merge.


.
.

Output Format

Do not write any output to stdout/console.

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.

Note: If the list is empty, will be null.

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

The following linked lists are passed as arguments to your function:

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:

Given , return the number in the sequence.

As an example, . The Fibonacci sequence to is . With zero-based indexing,


.

Function Description

Complete the recursive function in the editor below. It must return the element in the
Fibonacci sequence.

fibonacci has the following parameter(s):

n: the integer index of the sequence to return

Input Format

The input line contains a single integer, .

Constraints

Output Format

Locked stub code in the editor prints the integer value returned by the function.

Sample Input

Sample Output

Explanation

The Fibonacci sequence begins as follows:


...

We want to know the value of . In the sequence above, evaluates to .


Recursion: Davis'
Staircase
Davis has a number of staircases in his house and he likes to climb each staircase , , or steps at a
time. Being a very precocious child, he wonders how many ways there are to reach the top of the
staircase.

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

There are possible ways he can take these steps.

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.

stepPerms has the following parameter(s):

n: an integer, the number of stairs in the staircase

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

for of the maximum score.

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.

Thus, we print on a new line.


Crossword Puzzle
A Crossword grid is provided to you, along with a set of words (or names of places) which need to
be filled into the grid. Cells are marked either + or - . Cells marked with a - are to be filled with the word
list.

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.

crosswordPuzzle has the following parameter(s):

crossword: an array of strings of length representing the empty grid

words: a string consisting of semicolon delimited strings to fit into

Input Format

Each of the first lines represents , each of which has characters, .

The last line contains a string consisting of semicolon delimited to fit.

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:

Given an integer, we need to find the super digit of the integer.

If has only digit, then its super digit is .

Otherwise, the super digit of is equal to the super digit of the sum of the digits of .

For example, the super digit of will be calculated as:

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.

superDigit has the following parameter(s):

n: a string representation of an integer

k: an integer, the times to concatenate to make

Input Format

The first line contains two space separated integers, and .

Constraints

Output Format

Return the super digit of , where is created as described above.

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.

primality has the following parameter(s):

n: an integer to test for primality

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

We check the following integers for primality:

1. is divisible by numbers other than and itself (i.e.: , , ), so we print Not prime on a new
line.

2. is only divisible and itself, so we print Prime on a new line.

3. is only divisible and itself, so we print Prime on a new line.


Friend Circle Queries
The population of HackerWorld is . Initially, none of the people are friends with each other. In order to
start a friendship, two persons a and b have to shake hands, where . The friendship
relation is transitive, that is if a and b shake hands with each other, a and friends of a become friends with
b and friends of b.

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.

For example, your list of queries is:

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.

maxCircle has the following parameter(s):

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.

Codestub input format:


First line consist of an integer which denotes the number of queries to process.
Each of the next lines consists of two integers denoting the 2-D array .

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

Friend circles after each iteration:

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 .

maxXor has the following parameter(s):

arr: an array of integers

q: an array of integers to query

Input Format

The first line contains an integer , the size of the array .

The second line contains space-separated integers, from .

The third line contain , the size of the array .

Each of the next lines contains an integer where .

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

You might also like