Sei sulla pagina 1di 34

1.

Socks Merchant

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the
color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n = 7 socks with colors ar = [1, 2, 1, 2, 1, 3, 2] . There is one pair of color 1 and one of color 2 . There are three odd
socks left, one of each color. The number of pairs is 2.

Function Description

Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks
that are available.

sockMerchant has the following parameter(s):

• n: the number of socks in the pile


• ar: the colors of each sock

Input Format
The first line contains an integer n, the number of socks represented in ar .
The second line contains n space-separated integers describing the colors ar [i] of the socks in the pile.

Constraints
• 1 ≤ n ≤ 100
• 1 ≤ ar [i] ≤ 100 where 0 ≤ i ≤ n

Output Format
Return the total number of matching pairs of socks that John can sell.

Sample Input
9
10 20 20 10 10 30 50 10 20

Sample Output
3

Explanation

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static int sockMerchant(int n, int[] array) {


Set<Integer> colors = new HashSet<>();
int numPairs = 0;

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


if (!colors.add(array[i])) {
numPairs++;
colors.remove(array[i]);
}
}
return numPairs;
}
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

int[] ar = new int[n];

String[] arItems = scanner.nextLine().split(" ");


scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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


int arItem = Integer.parseInt(arItems[i]);
ar[i] = arItem;

int result = sockMerchant(n, ar);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

2. Counting Valleys

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took
exactly n steps. For every step he took, he noted if it was an uphill, U , or a downhill, D step. Gary's hikes start and end at sea level and each
step up or down represents a 1 unit change in altitude. We define the following terms:

• A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to
sea level.
• A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea
level.

Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is s = [DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out an up onto a mountain 2 units high.
Finally, he returns to sea level and ends his hike.

Function Description
Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameter(s):


• n: the number of steps Gary takes
• s: a string describing his path

Input Format
The first line contains an integer n, the number of steps in Gary's hike.
The second line contains a single string s, of n characters that describe his path.

Constraints
• 2 ≤ n ≤ 106
• S[i] ϵ {U D}

Output Format
Print a single integer that denotes the number of valleys Gary walked through during his hike.
Sample Input
8
UDDDUDUU

Sample Output
1

Explanation
If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:
_/\ _
\ /
\/\/
He enters and leaves one valley.

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static int countingValleys(String path) {


int level = 0;
int numValleys = 0;
for (char direction : path.toCharArray()) {
switch (direction) {
case 'D':
if (level-- == 0) numValleys++;
break;
case 'U':
level++;
break;
}
}
return numValleys;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

String s = scanner.nextLine();
int result = countingValleys(s);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

3. Jumping on the Clouds

Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are
cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid
the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is
always possible to win the game.
For each game, Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided. For example, c = [0, 1, 0, 0, 0, 1,
0] indexed from 0 … 6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 1 and 5. She could follow
the following two paths: 0 -> 2 -> 4 -> 6 or 0 -> 2 -> 3 -> 4 -> 6. The first path takes 3 jumps while the second takes 4.

Function Description
Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.

jumpingOnClouds has the following parameter(s):


• c: an array of binary integers

Input Format
The first line contains an integer n, the total number of clouds. The second line contains n space-separated binary integers describing
clouds c[i] where 0 ≤ i < n.

Constraints
• 2 ≤ n ≤ 100
• c[i] ϵ {0, 1}
• c[0] = c[n – 1] = 0

Output Format
Print the minimum number of jumps needed to win the game.

Sample Input 0
7
0010010

Sample Output 0
4

Explanation 0:
Emma must avoid c[2] and c[5]. She can win the game with a minimum of 4 jumps:

Sample Input 1
6
000010

Sample Output 1
3

Explanation 1:
The only thundercloud to avoid is c[4] . Emma can win the game in 3 jumps:
O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static int jumpingOnClouds(int[] clouds) {


int numClouds = clouds.length - 1;
int currCloud = 0;
int jumps = 0;

while (currCloud != numClouds) {


boolean canJumpOverCloud = (currCloud + 2 <= numClouds) && (clouds[currCloud + 2] == 0);
currCloud += canJumpOverCloud ? 2 : 1;
jumps++;
}
return jumps;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

int[] c = new int[n];

String[] cItems = scanner.nextLine().split(" ");


scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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


int cItem = Integer.parseInt(cItems[i]);
c[i] = cItem;
}

int result = jumpingOnClouds(c);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

4. Repeated String
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first n letters of Lilah's infinite string.
For example, if the string s = ‘abcac’ and n = 10, the substring we consider is abcacabcac, the first characters of her infinite string. There are
4 occurrences of a in the substring.

Function Description
Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of a in the
prefix of length n in the infinitely repeating string.

repeatedString has the following parameter(s):


• s: a string to repeat
• n: the number of characters to consider

Input Format
The first line contains a single string, s.
The second line contains an integer, n.

Constraints
• 1 ≤ |s| ≤ 100
• 1 ≤ n ≤ 1012
• For 25% of the test cases, n ≤ 106.

Output Format
Print a single integer denoting the number of letter a's in the first n letters of the infinite string created by repeating s infinitely many times.

Sample Input 0
aba
10

Sample Output 0
7

Explanation 0
The first n = 10 letters of the infinite string are abaabaabaa. Because there are 7 a's, we print 7 on a new line.

Sample Input 1
a
1000000000000

Sample Output 1
1000000000000

Explanation 1
Because all of the first n = 1000000000000 letters of the infinite string are a, we print 1000000000000 on a new line.

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static long repeatedString(String s, long n) {


long numOccurrences = s.replaceAll("[^a]", "").length();
if (numOccurrences == 0)
return numOccurrences;

long remainder = n % s.length();


long numRepetitions = n / s.length();
numOccurrences = numRepetitions * numOccurrences;
for (int i = 0; i < remainder; i++) {
if (s.charAt(i) == 'a') {
numOccurrences++;
}
}
return numOccurrences;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

String s = scanner.nextLine();

long n = scanner.nextLong();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

long result = repeatedString(s, n);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

5. 2D Array - DS

Given 6x6 a 2D Array, arr :

111000
010000
111000
000000
000000
000000

We define an hourglass in A to be a subset of values with indices falling in this pattern in arr's graphical representation:

abc
d
efg

There are 16 hourglasses in arr, and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in
arr, then print the maximum hourglass sum.

For example, given the 2D array:

-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 660
0 0 0 -2 0 0
0 0 1 240

We calculate the following 16 hourglass values:

-63, -34, -9, 12,


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

Our highest hourglass value is 28 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 6 lines of inputs arr[i] contains 6 space-separated integers .

Constraints
• -9 ≤ arr[i][j] ≤9
• 0 ≤ i,j ≤5

Output Format
Print the largest (maximum) hourglass sum found in arr.

Sample Input
111000
010000
111000
002440
000200
001240

Sample Output
19

Explanation
Arr contains the following hourglasses:

The hourglass with the maximum sum (19) is:


244
2
124

O que foi feito


import java.util.*;

public class Solution {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int[][] a = new int[6][6];
int max = Integer.MIN_VALUE;

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


for (int j = 0; j < 6; j++) {
a[i][j] = sc.nextInt();
if (i > 1 && j > 1) {
int sum = a[i][j]
+ a[i][j - 1]
+ a[i][j - 2]
+ a[i - 1][j - 1]
+ a[i - 2][j]
+ a[i - 2][j - 1]
+ a[i - 2][j - 2];

if (sum > max)


max = sum;
}
}
}

sc.close();
System.out.println(max);
}
}

6. Arrays: Left Rotation

A left rotation operation on an array shifts each of the array's elements unit to the left. For example, if 2 left rotations are performed on
array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].

Given an array a of n integers and a number, d, perform d 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 a.
• An integer d, the number of rotations.

Input Format
The first line contains two space-separated integers n and d, the size of a and the number of left rotations you must perform.
The second line contains n space-separated integers a[i].

Constraints
• 1 ≤ n ≤ 105
• 1≤d≤n
• 1 ≤ a[i] ≤106

Output Format
Print a single line n of space-separated integers denoting the final state of the array after performing d left rotations.

Sample Input
54
12345

Sample Output
51234

Explanation
When we perform d = 4 left rotations, the array undergoes the following sequence of changes:

[1,2,3,4,5] -> [2,3,4,5,1] -> [3,4,5,1,2] -> [4,5,1,2,3] -> [5,1,2,3,4]

O que foi feito


import java.util.*;

public class Solution {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
int idx = (i + n - k) % n;
a[idx] = in.nextInt();
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
in.close();
}
}

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

Function Description
Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No.

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, m and n, the numbers of words in the magazine and the note..
The second line contains m space-separated strings, each magazine[i].
The third line contains n space-separated strings, each note[i].

Constraints
• 1 ≤ m, n ≤ 30000
• 1 ≤ |magazine[i]|, |note[i]| ≤ 5
• Each word consists of English alphabetic letters (i.e. a to z and A to Z).

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

O que foi feito


import java.util.*;

public class Solution {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int m = in.nextInt();
int n = in.nextInt();

HashMap<String, Integer> magazine = new HashMap<>();


for (int i = 0; i < m; i++) {
String word = in.next();
magazine.put(word, magazine.getOrDefault(word, 0) + 1);
}
HashMap<String, Integer> ransom = new HashMap<>();
for (int i = 0; i < n; i++) {
String word = in.next();
ransom.put(word, ransom.getOrDefault(word, 0) + 1);
}
in.close();

if (magazine.size() < ransom.size()) {


System.out.println("No");
} else {
Optional<Integer> res = ransom.entrySet().stream()
.map(e -> magazine.getOrDefault(e.getKey(), 0) - e.getValue())
.filter(e -> e < 0)
.findFirst();
System.out.println(res.isPresent() ? "No" : "Yes");
}
}
}

8. 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 a. 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 s1.
• The second line contains string s2.

Constraints
• s1 and s2 consist of characters in the range ascii[a-z].
• 1 ≤ p ≤ 10
• 1 ≤ |s1|, |s2| ≤ 105
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 p=2 pairs to check:
1. s1 = “hello”, s2 = “world”. The substrings “o” and “l” are common to both strings.
2. a = “hi”, b = “world”. s1 and s2 share no common substrings.

O que foi feito

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

static String twoStrings(String s1, String s2) {


if (Pattern.compile("[" + s2 + "]").matcher(s1).find())
return "YES";
return "NO";
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int qItr = 0; qItr < q; qItr++) {


String s1 = scanner.nextLine();

String s2 = scanner.nextLine();

String result = twoStrings(s1, s2);

bufferedWriter.write(result);
bufferedWriter.newLine();
}

bufferedWriter.close();

scanner.close();

9. 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 numSwaps is the number of swaps that took place.
2. First Element: firstElement, where firstElement is the first element in the sorted array.
3. Last Element: lastElement, where lastElement 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 3 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, n, the size of the array a.
The second line contains n space-separated integers a[i].

Constraints
• 2 ≤ n ≤ 600
• 1 ≤ a[i] ≤ 2 x 106

Output Format
You must print the following three lines of output:
1. Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place.
2. First Element: firstElement, where is firstElement the first element in the sorted array.
3. Last Element: lastElement, where lastElement 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 0 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: {3, 2, 1}. The following 3 swaps take place:
1. {3, 2, 1} -> {2, 3, 1}
2. {2 ,3, 1} -> {2, 1, 3}
3. {2 ,1, 3} -> {1, 2, 3}
At this point the array is sorted and we print the necessary three lines of output shown above.

O que foi feito

import java.util.*;

public class Solution {

private static void bubbleSort(int[] array) {


int swaps = 0;
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 1; i < array.length; i++) {
if (array[i - 1] > array[i]) {
swap(array, i - 1, i);
swaps++;
swapped = true;
}

System.out.println("Array is sorted in " + swaps + " swaps.");


System.out.println("First Element: " + array[0]);
System.out.println("Last Element: " + array[array.length - 1]);
}

private static void swap(int[] array, int i, int j) {


int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
in.close();

bubbleSort(array);
}
}

10. Mark and Toys


Mark and Jane are very happy after having their first child. 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 prices = [1, 2, 3, 4] and
Mark has k = 7 to spend, he can buy items [1, 2, 3] for 6, or [3, 4] for 7 units of currency. He would choose the first group of 3 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, n and k, the number of priced toys and the amount Mark has to spend.
The next line contains n space-separated integers prices [i]

Constraints
• 1 ≤ n ≤ 105
• 1 ≤ k ≤ 109
• 1 ≤ prices[i] ≤ 109

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
4

Explanation
He can buy only 4 toys at most. These toys have the following prices: 1, 12, 5, 10.

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static int maximumToys(int[] prices, int k) {


Arrays.sort(prices);

int numToys = 0;
for (int price : prices) {
if (price <= k) {
numToys++;
k = k - price;
} else {
break;
}
}
return numToys;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nk = scanner.nextLine().split(" ");

int n = Integer.parseInt(nk[0]);
int k = Integer.parseInt(nk[1]);

int[] prices = new int[n];

String[] pricesItems = scanner.nextLine().split(" ");

scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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

int pricesItem = Integer.parseInt(pricesItems[i]);


prices[i] = pricesItem;
}

int result = maximumToys(prices, k);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();
scanner.close();
}
}

11. 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, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to
make a and b anagrams. Any characters can be deleted from either of the strings.

For example, if a = cde and b = dcf, we can delete e from string a and f from string b so that both remaining strings are cd and dc 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, a.
The second line contains a single string, b.

Constraints
• 1 ≤ |a|, |b| ≤ 104
• The strings a and b 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
4

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 4 characters to make both strings anagrams, so we print 4 on a new line.

O que foi feito

import java.util.*;

public class Solution {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
String a = in.nextLine();
String b = in.nextLine();
in.close();

HashMap<Character, Integer> map = new HashMap<>();


int difference = 0;

for (char letter : a.toCharArray()) {


map.put(letter, map.getOrDefault(letter, 0) + 1);
}

for (char letter : b.toCharArray()) {


if (!map.containsKey(letter) || map.get(letter) == 0)
difference++;
else
map.put(letter, map.get(letter) - 1);
}

for (char letter : map.keySet()) {


difference += map.get(letter);
}
System.out.println(difference);
}
}

12. Alternating Characters

You are given a string containing characters A and B 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 s= AABAAB, remove an A at positions 0 and 3 to make s = ABAB in 2 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 q, the number of queries.
The next q lines each contain a string s.

Constraints
• 1 ≤ q ≤ 10
• 1 ≤ |s| ≤ 105
• Each string s will consist only of characters A and B

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.

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static int alternatingCharacters(String s) {


int numDeletions = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
numDeletions++;
}
}
return numDeletions;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int qItr = 0; qItr < q; qItr++) {


String s = scanner.nextLine();

int result = alternatingCharacters(s);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();

scanner.close();

13. Minimum Absolute Difference in an Array

Consider an array of integers, arr = [arr[0], arr[1], …, arr [n-1]]. We define the absolute difference between two elements, a[i] and a[j]
(where i ≠ j), to be the absolute value of a[i] – a[j].

Given an array of integers, find and print the minimum absolute difference between any two elements in the array. For example, given the
array arr = [-2, 2,4] we can create 3 pairs of numbers: [-2, 2], [-2, 4] and [2, 4]. The absolute differences for these pairs are |(-2) -2| = 4, |(-2)
-4 = 6 and |2 -4| = 2. The minimum absolute difference is 2.

Function Description
Complete the minimumAbsoluteDifference function in the editor below. It should return an integer that represents the minimum absolute
difference between any pair of elements.

minimumAbsoluteDifference has the following parameter(s):


• n: an integer that represents the length of arr
• arr: an array of integers

Input Format
The first line contains a single integer n, the size of arr.
The second line contains n space-separated integers arr[i].

Constraints
• 2 ≤ n ≤ 105
• -109 ≤ arr[i] ≤ 109

Output Format
Print the minimum absolute difference between any two elements in the array.

Sample Input 0
3
3 -7 0

Sample Output 0
3

Explanation 0
With n = 3 integers in our array, we have three possible pairs: (3, -7), (3, 0), and (-7, 0). The absolute values of the differences between
these pairs are as follows:
• |3 - -7| -> 10
• |3 – 0| -> 3
• |-7 -0| -> 7

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

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 | -54 - -53| = 1.

Sample Input 2
5
1 -3 71 68 17

Sample Output 2
3

Explanation 2
The minimum absolute difference is |71 – 68| = 3.

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

// Complete the minimumAbsoluteDifference function below.


static int minimumAbsoluteDifference(int[] arr) {
Arrays.sort(arr);

int n = arr.length;
int minDifference = Integer.MAX_VALUE;

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


int currDifference = Math.abs(arr[i] - arr[i + 1]);
minDifference = Math.min(minDifference, currDifference);
if (minDifference == 0)
break;
}
return minDifference;
}
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();

scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

int[] arr = new int[n];

String[] arrItems = scanner.nextLine().split(" ");


scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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


int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;

int result = minimumAbsoluteDifference(arr);

bufferedWriter.write(String.valueOf(result));

bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();

}
14. Luck Balance

Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. Initially, her luck
balance is 0. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers, L[i] and T[i]:

• L[i]is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will decrease by L[i]; if she loses it, her luck
balance will increase by L[i].
• T[i] denotes the contest's importance rating. It's equal to 1 if the contest is important, and it's equal to 0 if it's unimportant.

If Lena loses no more than k 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, k =2 and:

Contest L[i] T[i]


1 5 1
2 1 1
3 4 0

If Lena loses all of the contests, her will be 5 + 1+ 4 = 10. Since she is allowed to lose 2 important contests, and there are only 2 important
contests. She can lose all three contests to maximize her luck at 10. If k = 1, she has to win at least 1 of the 2 important contests. She would
choose to win the lowest value important contest worth 1. Her final luck will be 5 + 4 – 1 = 8.

Function Description
Complete the luckBalance function in the editor below. It should return an integer that represents the maximum luck balance achievable.

luckBalance has the following parameter(s):


• k: the number of important contests Lena can lose
• contests: a 2D array of integers where each contests[i] contains two integers that represent the luck balance and importance of the ith
contest.

Input Format
The first line contains two space-separated integers n and k, the number of preliminary contests and the maximum number of important
contests Lena can lose.
Each of the next n lines contains two space-separated integers, L[i] and T[i], the contest's luck balance and its importance rating.

Constraints
• 1 ≤ n ≤ 100
• 0≤k≤N
• 1 ≤ L[i} ≤ 104
• T[i] ϵ {0, 1}

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 n=6 contests. Of these contests, 4 are important and she cannot lose more than k = 3 of them. Lena maximizes her luck if she
wins the 3rd important contest (where L[i] = 1) and loses all of the other five contests for a total luck balance of 5 + 2 +8 +10 + 5 -1 = 29.

O que foi feito


import java.io.*;
import java.util.*;
public class Solution {

public static void main(String[] args) throws IOException {


Scanner scanner = new Scanner(System.in);

int numContests = scanner.nextInt();


int maxLoses = scanner.nextInt();

int maxLuck = 0;

List<Integer> importantContests = new ArrayList<>();

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


int luck = scanner.nextInt();
int importance = scanner.nextInt();
maxLuck += luck;

if (importance == 1)
importantContests.add(luck);
}
scanner.close();

Collections.sort(importantContests);
for (int i = 0; i < importantContests.size() - maxLoses; i++) {
maxLuck -= 2 * importantContests.get(i);
}

System.out.println(maxLuck);
}
}

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

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 n, the number of nodes in the tree.
Next line contains n space separated integer where ith 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
• 1 ≤ node.data[i] ≤ 20
• 1 ≤ n ≤ 20

Output Format
Your function should return a single integer denoting the height of the binary tree.

Sample Input

Sample Output
3

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

There are 4 nodes in this path that are connected by 3 edges, meaning our binary tree's height = 3.

O que foi feito

import java.util.*;
class Node {
Node left;
Node right;
int data;

Node(int data) {
this.data = data;
left = null;
right = null;
}
}

class Solution {
public static int getHeight(Node root) {
if (root == null)
return -1;
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}

public static Node insert(Node root, int data) {


if (root == null) {
return new Node(data);
} else {
Node cur;
if (data <= root.data) {
cur = insert(root.left, data);
root.left = cur;
} else {
cur = insert(root.right, data);
root.right = cur;
}
return root;
}
}

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while (t-- > 0) {
int data = scan.nextInt();
root = insert(root, data);
}
scan.close();
int height = getHeight(root);
System.out.println(height);
}
}

16. Binary Search Tree: Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA)
of v1 and v2 in the binary search tree.

In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes 4 and 6
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, n, the number of nodes in the tree.
The second line contains n space-separated integers representing node.data values.
The third line contains two space-separated integers, v1 and v2.
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
• 1 ≤ n, node.data ≤ 25
• 1 ≤ v1, v2 ≤ 25
• v1 ≠ v2

The tree will contain nodes with data equal v1 to and v2.

Output Format
Return the a pointer to the node that is the lowest common ancestor of v1 and v2.

Sample Input
6
423176
17
v1 = 1and v2 = 7.

Sample Output
[reference to node 4]

Explanation
LCA of 1 and 7 is 4, the root in this case.
Return a pointer to the node.

O que foi feito

/* Node is defined as :
class Node
int data;
Node left;
Node right;
*/
static Node lca(Node root, int v1, int v2) {
if (root == null) return null;
if (v1 > v2) {
int temp = v2;
v2 = v1;
v1 = temp;
}
while (root.data < v1 || root.data > v2) {
if (root.data < v1) root = root.right;
else if (root.data > v2) root = root.left;
}
return root;
}

17. Insert a node at a specific position in a linked list

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 1 -> 2 -> 3 and you want to insert a node at position 2 with data = 4, your new list should be 1 -> 2 -> 4 ->
3

Function Description
Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list.

insertNodeAtPosition 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 n, the number of elements in the linked list.
Each of the next n lines contains an integer SinglyLinkedListNode[i].data.
The next line contains an integer data denoting the data of the node that is to be inserted.
The last line contains an integer position.

Constraints
• 1 ≤ n ≤ 1000
• 1 ≤ SinglyLinkedListNode[i].data ≤ 1000, where SinglyLinkedListNode[i] is the ith element of the linked list.
• 0 ≤ position ≤ n

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 1 at the position 2 which currently has 7 in it. The updated linked list will be 16 13 1 7

O que foi feito


import java.io.*

static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {


SinglyLinkedListNode new_node = new SinglyLinkedListNode(data);
SinglyLinkedListNode current_node = head

int index = 0;

while (index < position-1) {


current_node = current.node.next;
index++;
}

new_node.next = current_node.next;

return head;

18. Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer, data, create a new DoublyLinkedListNode object having data value data
and insert it into a sorted linked list while maintaining the sort.

Function Description
Complete the sortedInsert function in the editor below. It must return a reference to the head of your modified DoublyLinkedList.

sortedInsert has two parameters:


1. head: A reference to the head of a doubly-linked list of DoublyLinkedListNode objects.
2. data: An integer denoting the value of the data field for the DoublyLinkedListNode you must insert into the list.

Note: Recall that an empty list (i.e., where head = null) and a list with one element are sorted lists.

Input Format
The first line contains an integer t, the number of test cases.
Each of the test case is in the following format:
• The first line contains an integer n, the number of elements in the linked list.
• Each of the next n lines contains an integer, the data for each node of the linked list.
• The last line contains an integer data which needs to be inserted into the sorted doubly-linked list.

Constraints
• 1 ≤ t ≤ 10
• 1 ≤ n ≤ 1000
• 1 ≤ DoublyLinkedListNode.data ≤ 1000

Output Format
Do not print anything to stdout. Your method must return a reference to the head 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: 1 <-> 3 <-> 4 <-> 10 -> NULL.
The doubly linked list after insertion is: 1 <-> 3 <-> 4 <-> 5 <-> 10 -> NULL

O que foi feito


Node SortedInsert(Node head,int data) {
Node n = new Node();
n.data = data;
if (head == null) {
return n;
}
else if (data <= head.data) {
n.next = head;
head.prev = n;
return n;
}
else {
Node rest = SortedInsert(head.next, data);
head.next = rest;
rest.prev = head;
return head;
}
}

19. Reverse a doubly linked list

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 t, the number of test cases.

Each test case is of the following format:


• The first line contains an integer n, the number of elements in the linked list.
• The next n lines contain an integer each denoting an element of the linked list.

Constraints
• 1 ≤ t ≤ 10
• 0 ≤ n ≤ 1000
• 0 ≤ DoublyLinkedListNode.data ≤1000
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: 1 <-> 2 <-> 3 <-> 4 -> NULL
The reversed doubly linked list is: 4 <-> 3 <-> 2 <-> 1 -> NULL

O que foi feito

Altere no código da página apenas a palavra que está em vermelho aqui embaixo (altere o que está na linha 70):
static DoublyLinkedListNode reverse(DoublyLinkedListNode node) {

Colar este pedaço abaixo da linha 70 (sem deletar nada do código)


DoublyLinkedListNode curr = node;
DoublyLinkedListNode head = node;
while (curr != null) {
DoublyLinkedListNode temp = curr.prev;
curr.prev = curr.next;
curr.next = temp;
head = curr;
curr = curr.prev;
}
return head;
}

Obs.: pode ser que depois de você copiar, fique com 2 {‘s antes da string “private static final Scanner scanner .....”, você tem que
deixar somente uma

20. Find Merge Point of Two Lists

Given pointers to the head nodes of 2 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(SinglyLinkedListNode* (head1), SinglyLinkedListNode* (head2) 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(SinglyLinkedListNode,SinglyLinkedListNode) method has two parameters, head1 and head2, which are the non-null
head Nodes of two separate linked lists that are guaranteed to converge.

Constraints
The lists will merge.
• head1, head2 ≠ null.
• head 1 ≠ head2.
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 headA and headB are connected to. Recall that this is a
method-only challenge; the method only has initial visibility to those 2 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 2.
Test Case 1: As demonstrated in the diagram above, the merge Node's data field contains the integer 3

O que foi feito

import java.io.*;
import java.util.*;

public class Solution {

static class SinglyLinkedListNode {


public int data;
public SinglyLinkedListNode next;

public SinglyLinkedListNode(int nodeData) {


this.data = nodeData;
this.next = null;
}
}

static class SinglyLinkedList {


public SinglyLinkedListNode head;
public SinglyLinkedListNode tail;

public SinglyLinkedList() {
this.head = null;
this.tail = null;
}

public void insertNode(int nodeData) {


SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);

if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
}

public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException
{
while (node != null) {
bufferedWriter.write(String.valueOf(node.data));

node = node.next;

if (node != null) {
bufferedWriter.write(sep);
}
}
}

static int findMergeNode(SinglyLinkedListNode headA, SinglyLinkedListNode headB) {

SinglyLinkedListNode currentA = headA;


SinglyLinkedListNode currentB = headB;

// Do till the two nodes are the same


while (currentA != currentB) {
// If you reached the end of one list start at the beginning of the other one
if (currentA.next == null) {
currentA = headB;
} else {
currentA = currentA.next;
}

if (currentB.next == null) {
currentB = headA;
} else {
currentB = currentB.next;
}
}
return currentB.data;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {


BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int tests = scanner.nextInt();


scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int testsItr = 0; testsItr < tests; testsItr++) {


int index = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

SinglyLinkedList llist1 = new SinglyLinkedList();

int llist1Count = scanner.nextInt();


scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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


int llist1Item = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

llist1.insertNode(llist1Item);
}

SinglyLinkedList llist2 = new SinglyLinkedList();


int llist2Count = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

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


int llist2Item = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

llist2.insertNode(llist2Item);
}

SinglyLinkedListNode ptr1 = llist1.head;


SinglyLinkedListNode ptr2 = llist2.head;

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


if (i < index) {
ptr1 = ptr1.next;
}
}

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


if (i != llist2Count - 1) {
ptr2 = ptr2.next;
}
}

ptr2.next = ptr1;

int result = findMergeNode(llist1.head, llist2.head);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}

bufferedWriter.close();

scanner.close();
}
}

21. 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. For example, in the following graph
there is a cycle formed when node 5 points back to node 3.

Function Description
Complete the function has_cycle in the editor below. It must return a boolean true if the graph contains a cycle, or false.

has_cycle has the following parameter(s):


• head: a pointer to a Node object that points to the head of a linked list.

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

Input Format
There is no input for this challenge. A random linked list is generated at runtime and passed to your function.

Constraints
• 0 ≤ list size ≤ 100

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 0 to stdout.
2. The second list has a cycle, so we return true and the hidden code checker prints 1 to stdout.

O que foi feito


/*
Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.

A Node is defined as:


class Node {
int data;
Node next;
}
*/

//Tortoise and Hare algorithm


boolean hasCycle(Node head) {
if (head == null)
return false;

Node tortoise = head;


Node hare = head.next;
while (tortoise != hare) {
if (hare == null || hare.next == null)
return false;

tortoise = tortoise.next;
hare = hare.next.next;
}

return true;
}

22. Recursion: Fibonacci Numbers

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 fibonacci(0) = 0 and Fibonacci(1) = 1 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:
• fibonacci(0) = 0
• fibonacci(1) = 1
• fibonacci(n) = fibonacci(n -1) + fibonacci(n – 2)
Given n, return the nth number in the sequence.

As an example, n = 5. The Fibonacci sequence to 6 is fs = [0 , 1, 1, 2, 3, 5, 8]. With zero-based indexing, fs[5] = 5.

Function Description
Complete the recursive function fibonacci in the editor below. It must return the nth 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, n.

Constraints
• 0 ≤ n ≤ 30

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

Sample Input
3

Sample Output
2

Explanation
The Fibonacci sequence begins as follows:

fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(2) = (0 + 1) = 1
fibonacci(3) = (1 + 1) = 2
fibonacci(4) = (1 + 2) = 3
fibonacci(5) = (2 + 3) = 5
fibonacci(6) = (3 + 5) = 8

We want to know the value of fibonacci(3). In the sequence above, fibonnaci(3) evaluates to 2.

O que foi feito


Colar no espaço reservado o conteúdo em azul (o restante é para você ver que os códigos estão iguais)
import java.util.*;

public class Solution {

public static int fibonacci(int n) {


int prev = 0;
int curr = 1;
for (int i = 2; i <= n; i++) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
if (n < 2){
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
System.out.println(fibonacci(n));
}
}

Potrebbero piacerti anche