Category Archives: Pratice Problem

Set .add()

Task

Apply your knowledge of the .add() operation to help your friend Rupal.

Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps.

Find the total number of distinct country stamps.

Input Format

The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.

 

num = int(input())
country_name = set()
for i in range(num):
    country_name.add(input())
print(len(country_name))

Find the Second Largest Number

You are given N numbers. Store them in a list and find the second largest number.

Input Format
The first line contains N. The second line contains an array A[] of N integers each separated by a space.

 

 

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    print(sorted(list(set(arr)))[-2])

Game of Stones

Two players (numbered 1 and 2 ) are playing a game with n stones. Player 1 always plays first, and the two players move in alternating turns. The game’s rules are as follows:

  • In a single move, a player can remove either 2 ,3 , or 5 stones from the game board.
  • If a player is unable to make a move, that player loses the game.

Given the number of stones, find and print the name of the winner (i.e., First or Second) on a new line. Each player plays optimally, meaning they will not make a move that causes them to lose the game if some better, winning move exists.

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

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0){
            int n=sc.nextInt();
            if(n%7==0||n%7==1){
                System.out.println("Second");
            }else{
                System.out.println("First");
            }
        }
    }
}

Mini-Max Sum

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.

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

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long arr[]=new long[5];
arr[0]=in.nextLong();
long min=arr[0],max=arr[0],sum=arr[0];

for(int i=1;i<5;i++){
arr[i]=in.nextLong();
if(maxarr[i])
min=arr[i];
sum=sum+arr[i];
}
System.out.println((sum-max)+” “+(sum-min));

}
}

Matching Specific String

Task

You have a test string S. Your task is to match the string hackerrank. This is case sensitive.

Note

This is a regex only challenge. You are not required to write code.
You only have to fill in the regex pattern in the blank (_________).

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Regex_Test tester = new Regex_Test();
        tester.checker("hackerrank");
    }
}
class Regex_Test {
    public void checker(String Regex_Pattern){
        Scanner Input = new Scanner(System.in);
        String Test_String = Input.nextLine();
        Pattern p = Pattern.compile(Regex_Pattern);
        Matcher m = p.matcher(Test_String);
        int Count = 0;
        while(m.find()){
            Count += 1;
        }
        System.out.format("Number of matches : %d",Count);
    }
}

Insertion Sort(hackerrank problem)

Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms.

Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list.

Insert element into sorted list
Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted?

Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.

Guideline: You can copy the value of to a variable and consider its cell “empty”. Since this leaves an extra cell empty on the right, you can shift everything over until can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with .

Input Format
There will be two lines of input:

size – the size of the array
arr – the unsorted array of integers

Output Format
On each line, output the entire array every time an item is shifted in it.

Constraints

Sample Input

5
2 4 6 8 3

Sample Output

2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8

Task

Complete the method insertionSort which takes in one parameter:

arr – an array with the value in the right-most cell.

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

public class Solution {

public static void insertIntoSorted(int[] ar) {
// Fill up this function
int s=ar.length;
for(int i=s-1;i>=0;i–){
int v=ar[s-1];
int h=s-1;
while(h>=1&&ar[h-1]>v){
ar[h]=ar[h-1];
h–;
printArray(ar);
}
ar[h]=v;

}
printArray(ar);
}

/* Tail starts here */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertIntoSorted(ar);
}

private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}

}

Parenthesis Checker(java implementation)

Given an expression string exp, examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the program should print ‘balanced’ for exp = “[()]{}{[()()]()}” and ‘not balanced’ for exp = “[(])”

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

class GFG {
public static boolean isBalanced(String s){
Stackstack=new Stack();
for(int i = 0; i 0){
String st=sc.next();
//boolean bol=isBalanced(st);
if(isBalanced(st)){
System.out.println(“balanced”);
}else{
System.out.println(“not balanced”);
}

}
}
}