Coding Practice
Showing posts with label HackerRank Solution. Show all posts
Showing posts with label HackerRank Solution. Show all posts

Java Datatypes | HackerRank

Java Datatypes | HackerRank

Java has 8 primitive data types; char, boolean, byte, short, int, long, float, and double. For this exercise, we'll work with the primitives used to hold integer values (byte, short, int, and long):

  • A byte is an 8-bit signed integer.
  • A short is a 16-bit signed integer.
  • An int is a 32-bit signed integer.
  • A long is a 64-bit signed integer.

Given an input integer, you must determine which primitive data types are capable of properly storing that input.

To get you started, a portion of the solution is provided for you in the editor.

Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Input Format

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

Each test case, T, is comprised of a single line with an integer, n, which can be arbitrarily large or small.

Output Format

For each input variable n and appropriate primitive dataType, you must determine if the given primitives are capable of storing it. If yes, then print:

n can be fitted in:
* dataType

If there is more than one appropriate data type, print each one on its own line and order them by size (i.e.: byte < short < int < long).

If the number cannot be stored in one of the four aforementioned primitives, print the line:

n can't be fitted anywhere.

Sample Output
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long
Source Code
import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for(int i = 0; i < t; i++)
        {
            try
            {
                long x = sc.nextLong();

                System.out.println(x + " can be fitted in:");
                if(x >= -128 && x <= 127){
                    System.out.println("* byte");
                }
                if(x >= -32768 && x <= 32767){
                    System.out.println("* short");
                }
                if(x >= -2147483648 && x <= 2147483647){
                    System.out.println("* int");
                }
                if(x >= -9.22337204e18 && x <= 9.22337204e18){
                    System.out.println("* long");
                }
            }
            catch(Exception e)
            {
                System.out.println(sc.next() + " can't be fitted anywhere.");
            }

        }
    }
}
Sample Output
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long

Mini-Max Sum in C | HackerRank

Mini-Max Sum in C

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example

arr = [1, 3, 5, 7, 9]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints

16 24

Function Description

Complete the miniMaxSum function in the editor below.

miniMaxSum has the following parameter(s):

  • arr: an array of 5 integers

Print

Print two space-separated integers on one line: the minimum sum and the maximum sum of 4 of 5 elements.

Input Format

A single line of five space-separated integers.

Constraints

1 <= arr[i] <= 109

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

Sample Input

1 2 3 4 5

Sample Output

10 14

Explanation

The numbers are 1, 2, 3, 4, and 5. Calculate the following sums using four of the five integers:

  1. Sum everything except 1, the sum is 2 + 3 + 4 + 5 = 14.
  2. Sum everything except 2, the sum is 1 + 3 + 4 + 5 = 13.
  3. Sum everything except 3, the sum is 1 + 2 + 4 + 5 = 12.
  4. Sum everything except 4, the sum is 1 + 2 + 3 + 5 = 11.
  5. Sum everything except 5, the sum is 1 + 2 + 3 + 4 = 10.

Hints: Beware of integer overflow! Use 64-bit Integer.

Need help to get started? Try the Solve Me First problem

Sample Output
1 2 3 4 5
10 14
C-Source Code
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();
char** split_string(char*);

void miniMaxSum(int arr_count, int* arr) {
    
    int i, j;
    long sum[5] = {0};
 
        for (i = 0; i < arr_count; i++) {
 
            for (j = 0; j < arr_count; j++) {
 
                sum[i] = sum[i] + arr[j];
            }
            sum[i] = sum[i] - arr[i];
        }
        long min = sum[0], max = sum[0];
 
        for (i = 0; i < arr_count; i++) {
 
            if (sum[i] > max) {
 
                max = sum[i];
            }
            if (sum[i] < min) {
 
                min = sum[i];
            }
        }
        printf("%ld %ld", min, max);
}

int main()
{
    char** arr_temp = split_string(readline());

    int* arr = malloc(5 * sizeof(int));

    for (int i = 0; i < 5; i++) {
        char* arr_item_endptr;
        char* arr_item_str = *(arr_temp + i);
        int arr_item = strtol(arr_item_str, &arr_item_endptr, 10);

        if (arr_item_endptr == arr_item_str || *arr_item_endptr != '\0') { exit(EXIT_FAILURE); }

        *(arr + i) = arr_item;
    }

    int arr_count = 5;

    miniMaxSum(arr_count, arr);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;
    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) { break; }

        data_length += strlen(cursor);

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    }

    data = realloc(data, data_length);

    return data;
}

char** split_string(char* str) {
    char** splits = NULL;
    char* token = strtok(str, " ");

    int spaces = 0;

    while (token) {
        splits = realloc(splits, sizeof(char*) * ++spaces);
        if (!splits) {
            return splits;
        }

        splits[spaces - 1] = token;

        token = strtok(NULL, " ");
    }

    return splits;
}
Sample Output
1 2 3 4 5
10 14

Mini-Max Sum in Java | HackerRank

Mini-Max Sum in Java

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example

arr = [1, 3, 5, 7, 9]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints

16 24

Function Description

Complete the miniMaxSum function in the editor below.

miniMaxSum has the following parameter(s):

  • arr: an array of 5 integers

Print

Print two space-separated integers on one line: the minimum sum and the maximum sum of 4 of 5 elements.

Input Format

A single line of five space-separated integers.

Constraints

1 <= arr[i] <= 109

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

Sample Input

1 2 3 4 5

Sample Output

10 14

Explanation

The numbers are 1, 2, 3, 4, and 5. Calculate the following sums using four of the five integers:

  1. Sum everything except 1, the sum is 2 + 3 + 4 + 5 = 14.
  2. Sum everything except 2, the sum is 1 + 3 + 4 + 5 = 13.
  3. Sum everything except 3, the sum is 1 + 2 + 4 + 5 = 12.
  4. Sum everything except 4, the sum is 1 + 2 + 3 + 5 = 11.
  5. Sum everything except 5, the sum is 1 + 2 + 3 + 4 = 10.

Hints: Beware of integer overflow! Use 64-bit Integer.

Need help to get started? Try the Solve Me First problem

Sample Output
1 2 3 4 5
10 14
Java-Source Code
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    static void miniMaxSum(int[] arr) {
        int i, j;
        long sum[] = new long[5];

        for (i = 0; i < arr.length; i++) {

            for (j = 0; j < arr.length; j++) {

                sum[i] = sum[i] + arr[j];
            }
            sum[i] = sum[i] - arr[i];
        }
        long min = sum[0], max = sum[0];

        for (i = 0; i < arr.length; i++) {

            if (sum[i] > max) {

                max = sum[i];
            }
            if (sum[i] < min) {

                min = sum[i];
            }
        }
        System.out.println(min + " " + max);
    }

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

    public static void main(String[] args) {
        int[] arr = new int[5];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < 5; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        miniMaxSum(arr);

        scanner.close();
    }
}
Sample Output
1 2 3 4 5
10 14

Java Loops II | HackerRank

Java Loops II

We use the integers a, b, and n to create the following series:

(a + 20.b), (a + 20.b + 21.b),..., (a + 20.b + 21.b +...+ 2n-1.b)

You are given q queries in the form of a, b, and n. For each query, print the series corresponding to the given a, b, and n values as a single line of n space-separated integers.

Input Format

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

Each line i of the q subsequent lines contains three space-separated integers describing the respective ai, bi, and ni values for that query.

Constraints

  • 0 <= q <= 500
  • 0 <= a, b <= 50
  • 1 <= n <= 15

Output Format

For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of n space-separated integers.

Sample Input

2
0 2 10
5 3 5

Sample Output

2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98

Explanation

We have two queries:

1. We use a = 0, b = 2, and c = 10 to produce some series ss1 and sn-1:

  • s0 =  0 + 1.2 = 2
  • s1 = 0 + 1.2 + 2.2 = 6
  • s2 = 0 + 1.2 + 2.2 + 4.2 = 14

... and so on.

Once we hit n = 10, we print the first ten terms as a single line of space-separated integers.

2. We use a = 5, b = 3, and n = 5 to produce some series ss1 and sn-1:

  • s0 =  5 + 1.3 = 8
  • s1 = 5 + 1.3 + 2.3 = 14
  • s2 = 5 + 1.3 + 2.3 + 4.3 = 26
  • s3 = 5 + 1.3 + 2.3 + 4.3 + 8.3 = 50
  • s4 = 5 + 1.3 + 2.3 + 4.3 + 8.3 + 16.3 = 98

We then print each element of our series as a single line of space-separated values.

Sample Output
2
0 2 10
5 3 5

2 6 14 30 62 126 254 510 1022 2046 
8 14 26 50 98
Source Code
import java.util.*;
import java.io.*;

public class Solution {

    public static void main(String[] argh) {

        Scanner in = new Scanner(System.in);

        int i, j, s, s2, x, t = in.nextInt();

        for(i = 0; i < t; i++) {

            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();

            s2 = 0;
            x = 1;

            for (j = 0; j < n; j++) {
                s = (x * b) + s2;
                System.out.print(+s+a+ " ");
                s2 = s;
                x = x * 2;
            }
            System.out.println();
        }
        in.close();
    }
}
Sample Output
2
0 2 10
5 3 5

2 6 14 30 62 126 254 510 1022 2046 
8 14 26 50 98


Java Loops I | HackerRank

Java Loops I

Objective

In this challenge, we're going to use loops to help us do some simple math.

Task

Given an integer, N, print its first 10 multiples. Each multiple N * i (where 1 <= i <= 10) should be printed on a new line in the form: N x i = result.

Input Format

A single integer, N.

Constraints

  • 2 <= N <= 20

Output Format

Print 10 lines of output; each line i (where 1 <= i <= 10) contains the result of N * i in the form:

N x i = result.

Sample Input

2

Sample Output

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Sample Output
2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Java-Source Code
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

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

    public static void main(String[] args) {
        int i, N = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for(i = 1; i <= 10; i++){
            //System.out.printf("%d x %d = %d\n", N, i, N*i);
            System.out.println(+N+" x "+i+" = "+N*i);
        }
        scanner.close();
    }
}
Sample Output
2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20


Java Output Formatting | HackerRank

Java Output Formatting

Java's System.out.printf function can be used to print formatted output. The purpose of this exercise is to test your understanding of formatting output using printf.

To get you started, a portion of the solution is provided for you in the editor; you must format and print the input to complete the solution.

Input Format

Every line of input will contain a String followed by an integer.

Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999.

Output Format

In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.

Sample Input

java 100
cpp 65
python 50

Sample Output

================================
java           100
cpp            065
python         050
================================

Explanation

Each String is left-justified with trailing whitespace through the first 15 characters. The leading digit of the integer is the 16th character, and each integer that was less than 3 digits now has leading zeroes.

Sample Output
java 100
cpp 65
python 50
================================
java           100 
cpp            065 
python         050 
================================
Java-Source Code
import java.util.Scanner;

public class Solution {
    
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++){
            String s1=sc.next();
            int x=sc.nextInt();
            System.out.printf("%-13s  %03d\n", s1, x);
        }
        System.out.println("================================");
    }
}
Sample Output
java 100
cpp 65
python 50
================================
java           100 
cpp            065 
python         050 
================================


Java Stdin and Stdout II | HackerRank Solution

Java Stdin and Stdout II

In this challenge, you must read an integer, a double, and a String from stdin, then print the values according to the instructions in the Output Format section below. To make the problem a little easier, a portion of the code is provided for you in the editor.

Note: We recommend completing Java Stdin and Stdout I before attempting this challenge.

Input Format

There are three lines of input:

  1. The first line contains an integer.
  2. The second line contains a double.
  3. The third line contains a String.

Output Format

There are three lines of output:

  1. On the first line, print String: followed by the unaltered String read from stdin.
  2. On the second line, print Double: followed by the unaltered double read from stdin.
  3. On the third line, print Int: followed by the unaltered integer read from stdin.

To make the problem easier, a portion of the code is already provided in the editor.

Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).

Sample Input

42
3.1415
Welcome to HackerRank's Java tutorials!

Sample Output

String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
Sample Output
42
3.1415
Welcome to HackerRank's Java tutorials!
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
Source Code
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
Sample Output
42
3.1415
Welcome to HackerRank's Java tutorials!
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42


Java Stdin and Stdout I | HackerRank Solution

Java Stdin and Stdout I

Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output).

One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example:

Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);

The code above creates a Scanner object named scanner and uses it to read a String and an int. It then closes the Scanner object because there is no more input to read, and prints to stdout using System.out.println(String). So, if our input is:

Hi 5

Our code will print:

myString is: Hi
myInt is: 5

Alternatively, you can use the BufferedReader class.

Task

In this challenge, you must read  integers from stdin and then print them to stdout. Each integer must be printed on a new line. To make the problem a little easier, a portion of the code is provided for you in the editor below.

Input Format

There are 3 lines of input, and each line contains a single integer.

Sample Input

42
100
125

Sample Output

42
100
125
Sample Output
42
100
125

42
100
125
Java-Source Code
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}
Sample Output
42
100
125

42
100
125


Java If-Else | HackerRank

Java If-Else

In this challenge, we test your knowledge of using if-else conditional statements to automate decision-making processes. An if-else statement has the following logical flow:

Wikipedia if-else flow chart

Source: Wikipedia

Task

Given an integer, n, perform the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird

Complete the stub code provided in your editor to print whether or not  is weird.

Input Format

A single line containing a positive integer, n.

Constraints

  • 1 <= n <= 100

Output Format

Print Weird if the number is weird; otherwise, print Not Weird.

Sample Input 0

3

Sample Output 0

Weird

Sample Input 1

24

Sample Output 1

Not Weird

Explanation

Sample Case 0: n = 3

n is odd and odd numbers are weird, so we print Weird.

Sample Case 1: n = 24

n > 20 and  is even, so it isn't weird. Thus, we print Not Weird.

Sample Output
3
Weird


...Program finished with exit code 0
Press ENTER to exit console.
Java-Source Code
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

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

    public static void main(String[] args) {
        int N = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
        if(N%2 == 0){
            if(N >= 2 && N <= 5){
                System.out.println("Not Weird");
            }
            else if(N >= 6 && N <= 20){
                System.out.println("Weird");
            }
            else if(N >= 20){
                System.out.println("Not Weird");
            }
        }
        else{
            System.out.println("Weird");
        }

        scanner.close();
    }
}
Sample Output
24
Not Weird


...Program finished with exit code 0
Press ENTER to exit console.


Welcome to Java! | HackerRank

Welcome to Java!

Welcome to the world of Java! In this challenge, we practice printing to stdout.

The code stubs in your editor declare a Solution class and a main method. Complete the main method by copying the two lines of code below and pasting them inside the body of your main method.

System.out.println("Hello, World.");

System.out.println("Hello, Java.");

Input Format

There is no input for this challenge.

Output Format

You must print two lines of output:

  1. Print Hello, World. on the first line.
  2. Print Hello, Java. on the second line.

Sample Output

Hello, World.

Hello, Java.

Sample Output
Hello, World.
Hello, Java.


...Program finished with exit code 0
Press ENTER to exit console.
Java-Source Code
public class Solution {

    public static void main(String[] args) {
        System.out.println("Hello, World.");
        System.out.println("Hello, Java.");
    }
}
Sample Output
Hello, World.
Hello, Java.


...Program finished with exit code 0
Press ENTER to exit console.


Arrays: Left Rotation | Java HackerRank

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 [1,2,3,4,5], then the array would become [3,4,5,1,2]. Note that the lowest index item moves to the highest index in a rotation. This is called a circular array.

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.

rotLeft has the following parameter(s):

  • int a[n]: the array to rotate
  • int d: the number of rotations

Returns

  • int a'[n]: the rotated array

Input Format

The first line contains two space-separated integers n and d, the size of a and the number of left rotations.

The second line contains n space-separated integers, each an a[i].

Constraints

  • 1 <= n <= 105
  • 1 <= d <= n
  • 1 <= a[i] <= 106

Sample Input

5 4

1 2 3 4 5

Sample Output

5 1 2 3 4

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]

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


...Program finished with exit code 0
Press ENTER to exit console.
Source Code
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    static int[] rotLeft(int[] a, int d, int n) {

        int i, j, k, b[] = new int[n], c[] = new int[n];

        for(i = d, j = 0, k = 0; j < n; j++){

            b[j] = a[j];

            if(j > d-1){
                a[k] = a[i];
                k++;
                i++;
            }
            else{
                c[j] = b[j];
            }
        }
        for(i = n-d, j = 0; i < n; i++, j++){
            
            a[i] = c[j];
        }
        
        return a;

    }

    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[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);

        int d = Integer.parseInt(nd[1]);

        int[] a = new int[n];

        String[] aItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int aItem = Integer.parseInt(aItems[i]);
            a[i] = aItem;
        }

        int[] result = rotLeft(a, d, n);

        for (int i = 0; i < result.length; i++) {
            bufferedWriter.write(String.valueOf(result[i]));

            if (i != result.length - 1) {
                bufferedWriter.write(" ");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}
Sample Output
5 4
1 2 3 4 5
5 1 2 3 4


...Program finished with exit code 0
Press ENTER to exit console.

Java String Reverse - Palindrome | Java HackerRank

Java String Reverse

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.(Wikipedia)

Given a string A, print Yes if it is a palindrome, print No otherwise.

Constraints

  • A will consist at most 50 lower case English letters.

Sample Input

madam

Sample Output

Yes

Sample Output
madam
Yes


...Program finished with exit code 0
Press ENTER to exit console.
Source Code
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        String A = sc.next();
        String B = "";
        int i, j, length = A.length();

        for(i = length - 1, j = 0; i >= 0; i--, j++){

            B = B + A.charAt(i);
        }
        if(B.equals(A)){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }
        
    }
}
Sample Output
java
No


...Program finished with exit code 0
Press ENTER to exit console.


Java Substring Comparisons | Java HackerRank

Java Substring Comparisons
We define the following terms:
A < B <...< Y < Z < a < b <...< y < z
For example, ball < cat, dog < dorm, Happy < happy, Zoo < ball.
  • A substring of a string is a contiguous block of characters in the string. For example, the substrings of abc are a, b, c, ab, bc, and abc.
Given a string, s, and an integer, k, complete the function so that it finds the lexicographically smallest and largest substrings of length k.

Input Format

The first line contains a string denoting s.
The second line contains an integer denoting k.

Constraints

  • 1 <= |s| <= 1000
  • s consists of English alphabetic letters only (i.e., [a-zA-Z]).

Output Format

Return the respective lexicographically smallest and largest substrings as a single newline-separated string.

Sample Input 0

welcometojava
3

Sample Output 0

ava
wel

Explanation 0

String s = "welcometojava" has the following lexicographically-ordered substrings of length k = 3:

["ava", "com", "elc", "eto", "jav", "lco", "met", "oja", "ome", "toj", "wel"]

We then return the first (lexicographically smallest) substring and the last (lexicographically largest) substring as two newline-separated values (i.e., ava\nwel).

The stub code in the editor then prints ava as our first line of output and wel as our second line of output.

Sample Output
welcometojava
3
ava
wel


...Program finished with exit code 0
Press ENTER to exit console.
Source Code
import java.util.Scanner;

public class Main {

    public static String getSmallestAndLargest(String s, int k) {
        
        int i, j, length;

        String temp = "";
        String smallest = s.substring(0, k);
        String largest = "";
        
        for(i = 0; i <= s.length()-k; i++){

            temp = s.substring(i, (i+k));

            if(temp.compareTo(smallest) <= 0){

                smallest = temp;
            }
            if(temp.compareTo(largest) >= 0){

                largest = temp;
            }
        }
        return smallest + "\n" + largest;
    }


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        int k = scan.nextInt();
        scan.close();
      
        System.out.println(getSmallestAndLargest(s, k));
    }
}
Sample Output
welcometojava
3
ava
wel


...Program finished with exit code 0
Press ENTER to exit console.


HackerRank Solution in Java Language

HackerRank Solution in C Language

Solve Me First in C | HackerRank

Solve Me First in C

Complete the function solveMeFirst to compute the sum of two integers.

Example

a = 7

b = 3

Return 10.

Function Description

Complete the solveMeFirst function in the editor below.

solveMeFirst has the following parameters:

  • int a: the first value
  • int b: the second value

Returns

- int: the sum of a and b

Constraints

1 <= a, b <=1000

Sample Input:

a = 2

b = 3

Sample Output

5

Explanation

2 + 3 = 5

Sample Output
7
3
10


...Program finished with exit code 0
Press ENTER to exit console.
C-Source Code
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int solveMeFirst(int a, int b) {
    return a + b;
}

int main() {
    int num1,num2;
    scanf("%d %d",&num1,&num2);
    int sum; 
    sum = solveMeFirst(num1,num2);
    printf("%d",sum);
    return 0;
}
Sample Output
99
11
110


...Program finished with exit code 0
Press ENTER to exit console.


Solve Me First in Java | HackerRank

Solve Me First in Java

Complete the function solveMeFirst to compute the sum of two integers.

Example

a = 7

b = 3

Return 10.

Function Description

Complete the solveMeFirst function in the editor below.

solveMeFirst has the following parameters:

  • int a: the first value
  • int b: the second value

Returns

- int: the sum of a and b

Constraints

1 <= a, b <=1000

Sample Input:

a = 2

b = 3

Sample Output

5

Explanation

2 + 3 = 5

Sample Output
7
3
10


...Program finished with exit code 0
Press ENTER to exit console.
Java-Source Code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int solveMeFirst(int a, int b) {
        return a+b; 
	}

 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a;
        a = in.nextInt();
        int b;
        b = in.nextInt();
        int sum;
        sum = solveMeFirst(a, b);
        System.out.println(sum);
	}
}
Sample Output
99
11
110


...Program finished with exit code 0
Press ENTER to exit console.


Change Theme
X