[go: up one dir, main page]

0% found this document useful (0 votes)
601 views108 pages

Full Hackerrank

The document discusses various topics related to software development including team formation, load balancing, product defects, shape inheritance, perfect substring, work schedule, ways to sum, group division, employee implementation, counting pairs, counting permutation, balanced sum, balancing parenthesis, find before matrix, device name system, condensed list, grouping options, list inheritance, and sports inheritance. It provides code snippets and algorithms for counting vowels, removing duplicates from a linked list, and converting an array to a list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
601 views108 pages

Full Hackerrank

The document discusses various topics related to software development including team formation, load balancing, product defects, shape inheritance, perfect substring, work schedule, ways to sum, group division, employee implementation, counting pairs, counting permutation, balanced sum, balancing parenthesis, find before matrix, device name system, condensed list, grouping options, list inheritance, and sports inheritance. It provides code snippets and algorithms for counting vowels, removing duplicates from a linked list, and converting an array to a list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

TEAM FORMATION

9/15 test cases passing


LOAD BALANCING
10/15 test cases passing
PRODUCT DEFECTS
SHAPE INHERITANCE
PERFECT SUBSTRING
WORK SCHEDULE
WAYS TO SUM
OR (parameters are different)
static int countWays(int N)
{
int count[] = new int[N + 1];

// base case
count[0] = 1;

// count ways for all values up


// to 'N' and store the result
for (int i = 1; i <= N; i++)
for (int j = 0; j < arr.length; j++)

// if i >= arr[j] then


// accumulate count for value 'i' as
// ways to form value 'i-arr[j]'
if (i >= arr[j])
count[i] += count[i - arr[j]];

// required number of ways


return count[N];

}
GROUP DIVISION

EMPLOYEE IMPLEMENTATION
COUNTING PAIRS
OR

COUNTING PERMUTATION
OR

OR
public class Solution {

private static final int MOD = 1000000007;

public int countVowelPermutation(int n) {

long[] current = new long[]{1,1,1,1,1};

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

long[] next = new long[]{0,0,0,0,0};

// Each vowel 'a' may only be followed by an 'e'.

next[1] += current[0];

// Each vowel 'e' may only be followed by an 'a' or an 'i'.

next[0] += current[1];
next[2] += current[1];

// Each vowel 'i' may not be followed by another 'i'.

next[0] += current[2];

next[1] += current[2];

next[3] += current[2];

next[4] += current[2];

// Each vowel 'o' may only be followed by an 'i' or a 'u'.

next[2] += current[3];

next[4] += current[3];

// Each vowel 'u' may only be followed by an 'a'.

next[0] += current[4];

// assign

current[0] = next[0] % MOD;

current[1] = next[1] % MOD;

current[2] = next[2] % MOD;

current[3] = next[3] % MOD;

current[4] = next[4] % MOD;

return (int)((current[0]+current[1]+current[2]+current[3]+current[4]) % MOD);

public static void main(String args[]) {

Solution s = new Solution();

System.out.println(s.countVowelPermutation(1));

System.out.println(s.countVowelPermutation(2));

System.out.println(s.countVowelPermutation(5));

System.out.println(s.countVowelPermutation(20000));

}
BALANCED SUM

OR
BALANCING PARANTHESIS

GET MINIMUM

OR
FIND BEFORE MATRIX
DIVICE NAME SYSTEM

OR
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class test {

public static List<String>


deviceNamesSystem(List<String> devicenames){
Map<String,Integer> devNumList=new
HashMap<String,Integer>();
List<String> newNameList=new
ArrayList<String>();
for(String s:devicenames) {
if(devNumList.containsKey(s)) {

newNameList.add(s+devNumList.get(s));
devNumList.replace(s,
devNumList.get(s)+1);
}
else {
newNameList.add(s);
devNumList.put(s, 1);
}
}
return newNameList;
}
public static void main(String[] args) {

List<String> deviceNames=new
ArrayList<String>();
deviceNames.add("Switch");
deviceNames.add("tv");
deviceNames.add("Switch");
deviceNames.add("tv");
deviceNames.add("Switch");
deviceNames.add("tv");
deviceNames.add("Switch");
deviceNames.add("tv");

deviceNames=deviceNamesSystem(deviceNames);
deviceNames.forEach(x-
>System.out.println(x));
}

CONDENSED LIST

OR
// Java program to remove duplicates from unsorted
// linked list

class LinkedList {

static Node head;


static class Node {

int data;
Node next;

Node(int d) {
data = d;
next = null;
}
}

/* Function to remove duplicates from an


unsorted linked list */
void remove_duplicates() {
Node ptr1 = null, ptr2 = null, dup = null;
ptr1 = head;

/* Pick elements one by one */


while (ptr1 != null && ptr1.next != null) {
ptr2 = ptr1;

/* Compare the picked element with rest


of the elements */
while (ptr2.next != null) {

/* If duplicate then delete it */


if (ptr1.data == ptr2.next.data) {

/* sequence of steps is
important here */
dup = ptr2.next;
ptr2.next = ptr2.next.next;
System.gc();
} else /* This is tricky */ {
ptr2 = ptr2.next;
}
}
ptr1 = ptr1.next;
}
}

void printList(Node node) {


while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}

public static void main(String[] args) {


LinkedList list = new LinkedList();
list.head = new Node(3);
list.head.next = new Node(4);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(2);
list.head.next.next.next.next = new Node(6);
list.head.next.next.next.next.next = new
Node(1);
list.head.next.next.next.next.next.next = new
Node(2);
list.head.next.next.next.next.next.next.next = new
Node(6);

System.out.println("Linked List before


removing duplicates : \n ");
list.printList(head);

list.remove_duplicates();
System.out.println("");
System.out.println("Linked List after removing
duplicates : \n ");
list.printList(head);
}
}

GROUPING OPTIONS
LIST INHERITANCE
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

interface MyList {
void convert(String[] a);

void replace(int idx);

ArrayList<String> compact();
}

class InvalidStringException extends Exception {

private static final long serialVersionUID = 1L;

public InvalidStringException() {
super();
}
}

class ArrayToList implements MyList {

ArrayList<String> arrayToList;

public ArrayToList() {
arrayToList = new ArrayList<>();
}

@Override
public void convert(String[] a) {
for (int i = 0; i < a.length; i++) {
arrayToList.add(a[i]);
System.out.println("I have added the string: " +
a[i] + " at the index: " + i);
}
}

@Override
public void replace(int idx) {
String string = arrayToList.get(idx);
arrayToList.set(idx, null);
System.out.println("I have replaced the string: " +
string + " with a null string ");
}

@Override
public ArrayList<String> compact() {
arrayToList.removeAll(Collections.singleton(null));
return arrayToList;
}

}
public class Solution {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
String[] a = new String[n];

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


a[i] = sc.next();
}

ArrayToList arrayToList = new ArrayToList();

arrayToList.convert(a);

arrayToList.replace(1);

arrayToList.compact();

sc.close();
}

OR
class InvalidStringException extends Exception {
public InvalidStringException(String s)
{
super(s);
}
}

class ArrayToList implements MyList{


private ArrayList<String> darray=new ArrayList<>();
private int index=0;
private String n;
public ArrayToList( )
{

}
public void convert(String[] a)
{
for(int i=0;i<a.length;i++)
{
darray.add(i,a[i]);
index=darray.indexOf(a[i]);
System.out.println("I have added the string: "+a[i]+" at
the index: "+i);
}
}
public void replace(int idx){
n=darray.get(idx);
darray.set(idx, "");
System.out.println("I have replaced the string: "+n+"
with a null string");
}
public ArrayList<String> compact()
{
darray.removeAll(Arrays.asList(""));
return darray;
}

SPORTS INHERITANCE
package test;
import java.util.*;
import java.io.*;

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
interface Sport{
void calculateAvgAge(int[] age);
void retirePlayer(int id);
}

class Cricket implements Sport{


public int playerIDs[];

Cricket(){
playerIDs=new int[11];
for(int i=0;i<11;i++) {
playerIDs[i]=1;
}
System.out.println("A new cricket team has been
formed");
}

public void calculateAvgAge(int[] age) {


double sum=0;
int n=age.length;
for(int i=0;i<n;i++) {
sum+=age[i];
}
double avgAge=sum/n;
System.out.format("The average age of team is
%.2f",avgAge);
}

public void retirePlayer(int id) {


if(playerIDs[id]==-1) {
System.out.println("Player has already
retired");
}else {
playerIDs[id]=-1;
System.out.println("Player with id: "+id+" has
retired");
}
}
}

class Football implements Sport{


public int playerIDs[];

Football(){
playerIDs=new int[11];
for(int i=0;i<11;i++) {
playerIDs[i]=1;
}
System.out.println("A new football team has been
formed");
}

public void calculateAvgAge(int[] age) {


double sum=0;
int n=age.length;
for(int i=0;i<n;i++) {
sum+=age[i];
}
double avgAge=sum/n;
System.out.format("The average age of team is
%.2f",avgAge);
}

public void retirePlayer(int id) {


if(playerIDs[id-1]==-1) {
System.out.println("Player has already
retired");
}else {
playerIDs[id-1]=-1;
System.out.println("Player with id: "+id+" has
retired");
}
}

public void playerTransfer(int fee,int id) {


if(playerIDs[id]==-1) {
System.out.println("Player has already
retired");
} else {
System.out.println("Player with id: "+id+" has
been transferred with a fee of "+fee);
}
}
}

public class Test {

private static final Scanner scanner = new


Scanner(System.in);
public static void main(String[] args) throws
IOException {

int age[]= {26,32,36,33,24,31,30,35,36,21,28};


Cricket obj=new Cricket();
obj.calculateAvgAge(age);
obj.retirePlayer(5);
obj.retirePlayer(5);

}
}
CRICKET SPORTS
CAR INHERITANCE
class WagonR extends Car{
int mileage;
public WagonR(Integer mileage){
super(false, "4");
this.mileage = mileage;
}
@Override
public String getMileage(){
String mil=Integer.toString(mileage);
return mileage+" kmpl";
}
}

class HondaCity extends Car{


int mileage;
public HondaCity(Integer mileage){
super(true, "4");
this.mileage = mileage;

@Override
public String getMileage(){
String mil=Integer.toString(mileage);
return mil+" kmpl";
}
}

class InnovaCrysta extends Car{


int mileage;
public InnovaCrysta(Integer mileage){

super(false, "6");
this.mileage = mileage;

@Override
public String getMileage(){
String mil=Integer.toString(mileage);
return mil+" kmpl";
}
}

PRISON BREAK
Matrix Summation
Merge 2 arrays
NUMBER OF MOVES
OR
class Solution {

// Class for storing a Point's data

static class Point {

int x, y;

int dis;

public Point(int x, int y, int dis)

this.x = x;
this.y = y;

this.dis = dis;

// Utility method returns true if (x, y) lies

// inside Board

static boolean isInside(int x, int y, int N)

if (x >= 0 && x < N && y >= 0 && y < N)

return true;

return false;

public static int minMoves(int n, int startRow, int startCol, int endRow, int
endCol) {

int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 };

int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 };

int minDistance = Integer.MAX_VALUE;

Queue<Point> queue = new ArrayDeque<>();

queue.add(new Point(startRow, startCol,0));

Point t;

int x, y;

boolean visit[][] = new boolean[n][n];

// make all Point unvisited

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

for (int j = 0; j < n; j++)

visit[i][j] = false;

visit[startRow][startCol] = true;

while (!queue.isEmpty()) {

t = queue.poll();
if (t.x == endRow && t.y == endCol){

if(minDistance > t.dis)

minDistance = t.dis;

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

x = t.x + dx[i];

y = t.y + dy[i];

// If reachable state is not yet visited and

// inside board, push that state into queue

if (isInside(x, y, n) && !visit[x][y]) {

visit[x][y] = true;

queue.add(new Point(x, y, t.dis + 1));

return minDistance == Integer.MAX_VALUE? -1:minDistance;

// Driver code

public static void main(String[] args)

System.out.println( minMoves(7, 6, 6, 1,0));

JAVA EXCEPTIONS: SECURING MESSAGES


package com.nastra.hackerrank;

import com.nastra.hackerrank.util.FastScanner;
public class Encryption {

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


FastScanner sc = new FastScanner(System.in);
String word = sc.next();

System.out.println(solve(word));
}

private static String solve(String word) {


char[][] squareCode = encrypt(word);
StringBuilder out = new StringBuilder();

int maxRows = squareCode.length;


int maxCols = squareCode[0].length;

int row = 0;
int col = 0;

while (true) {
if (row >= maxRows) {
row = 0;
col++;
out.append(" ");
}
if (col >= maxCols) {
break;
}
char c = squareCode[row][col];
if (c == '~') {
row++;
continue;
} else {
out.append(c);
}
row++;
}

return out.toString().trim();
}

private static char[][] encrypt(String word) {


int len = word.length();
double row = Math.floor(Math.sqrt((double) len));
double col = Math.ceil(Math.sqrt((double) len));

// find smallest possible area where all characters fit into


if (((int) row * col) < len) {
double min = Math.min(row, col);
if (min == row) {
row++;
} else {
col++;
}
}

char[][] squareCode = new char[(int) row][(int) col];


int k = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (k < len) {
squareCode[i][j] = word.charAt(k);
k++;
} else {
squareCode[i][j] = '~';
}
}
}
return squareCode;
}
}

SUB STRING DIVISIBILITY


public class PE043_Sub_string_divisibility {
private static int[] primeList = { 2, 3, 5, 7, 11, 13, 17 };
private static String[][] modList;
private static long result = 0;
private static String numbers = "0123456789";

public static void main(String[] args) {


long start = System.nanoTime();

modList = new String[primeList.length][];


int prime;

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


prime = primeList[i];
modList[i] = new String[prime];

for (int j = 0; j < prime; j++) {


modList[i][j] = new String("");
}

for (int j = 0; j < 1000; j += 100) {


if (j % prime == 0) {
modList[i][0] += (j / 100);
} else {
modList[i][(j / prime + 1) * prime % j] +=
(j / 100);
}
}
}
String mult17str;

for (int i = 102; i < 1003; i += 17) {


if (!isValid(mult17str = String.valueOf(i))) {
continue;
} else {
findSolutions(mult17str);
}
}

long end = System.nanoTime();


long runtime = end - start;
System.out.println(result);
System.out.println("Runtime: " + runtime / 1000000 +
"ms (" + runtime
+ "ns)");
}

private static void findSolutions(String number) {


if (number.length() == 9 && isValid(number)) {
boolean found = false;
int i;

for (i = 0; !found && i < numbers.length(); i++) {


if (number.indexOf(numbers.charAt(i)) == -1) {
found = true;
}
}

i--;

if (i != 0) {
result += Long.parseLong(String.valueOf(i) +
number);
}
} else {
int primeIndex = primeList.length - number.length()
+ 1;
int mod = Integer.parseInt(number.substring(0, 2))
% primeList[primeIndex];
String newNumber;

for (int i = 0; i < modList[primeIndex][mod].length();


i++) {
if (isValid(newNumber =
modList[primeIndex][mod].substring(i,
i + 1) + number)) {
findSolutions(newNumber);
}
}
}
}

private static boolean isValid(String number) {


boolean valid = true;
for (int i = 0; valid && i < number.length() - 1; i++) {
if (number.indexOf(number.charAt(i), i + 1) != -1) {
valid = false;
}
}

return valid;
}
}

MINIMUM SUM
Don’t know the correctness
public static int minSum(List<Integer> nums, int k) {

Queue<Integer> maxPq = new PriorityQueue<>(nums.size(),


Comparator.reverseOrder());

maxPq.addAll(nums);

while (k-- > 0) {

int num = (int) Math.ceil(maxPq.poll() / 2.0);

maxPq.add(num);

return maxPq.stream().mapToInt(i -> i).sum();

OR
Some test cases may not pass due to time complexity
function minSum(num, k) {

var sum = 0;

var i = 0;

var firstMaxIndex = 0;

var secondMaxIndex = 1;
if (num.length == 0) {

return 0;

if(num.length == 1) {

num[0] = Math.ceil(num[0]/2);

num.sort((a, b) => b-a);

while (k > 0) {

var result = Math.ceil(num[i] / 2);

num[i] = result;

if (num[secondMaxIndex] > result) {

// second item is larger than first now.

// put the first item in right position

var maxNum = num[firstMaxIndex];

for (var j = secondMaxIndex; j < num.length; j++) {

if (num[j] > maxNum) {

num[j - 1] = num[j];

} else {

break;

num[j - 1] = maxNum;

k--;
}

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

sum += num[j];

return sum;

SMALLEST SET COVERING INTERVALS

OR
package com.be1ive.hackerrank.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

public class IntervalSelection {

public static class Interval implements Comparable<Interval> {

public final int a, b;

public Interval(int a, int b) {


this.a = a;
this.b = b;
}

@Override
public int compareTo(Interval that) {
int cmp = Integer.compare(this.b, that.b);

if (cmp == 0) {
return Integer.compare(this.a, that.a);
} else {
return cmp;
}
}

@Override
public String toString() {
return "Line{" +
"a=" + a +
", b=" + b +
'}';
}
}

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

BufferedReader reader = new BufferedReader(new


InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);

int T = Integer.parseInt(reader.readLine());

for(int t = 0; t < T; t++){


int N;
N = Integer.parseInt(reader.readLine());

int A[] = new int[N];


int B[] = new int[N];
Interval[] I = new Interval[N];

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


String[] s = reader.readLine().split(" ");
A[i] = Integer.parseInt(s[0]);
B[i] = Integer.parseInt(s[1]);
I[i] = new Interval(A[i], B[i]);
}

Arrays.sort(I);

int result = 1;
int permitStart = 1;
Interval interval = I[0];
for (int i = 1; i<N; i++) {
if (I[i].a >= permitStart) {
result++;
if (interval.b >= I[i].a) {
permitStart = interval.b + 1;
}
interval = I[i];
}
}

writer.println(result);
}
writer.flush();
writer.close();
}
}
EVEN SUBARRAY
import java.io.*;

class GFG
{
static int countEvenSum(int arr[],
int n)
{
int result = 0;

// Find sum of all subarrays


// and increment result if
// sum is even
for (int i = 0; i <= n - 1; i++)
{
int sum = 0;
for (int j = i; j <= n - 1; j++)
{
sum = sum + arr[j];
if (sum % 2 == 0)
result++;
}
}

return (result);
}

// Driver code
public static void main (String[] args)
{
int arr[] = {1, 2, 2,
3, 4, 1};
int n = arr.length;

System.out.print("The Number of Subarrays"+


" with even sum is ");

System.out.println(countEvenSum(arr, n));
}
}

DIVISIBILITY OF STRINGS
Code is in c#. 12/14 test cases passing.

OR
function findSmallestDivisor(s, t) {

if (!s || s.length == 0 || !t || t.length == 0) {

return -1;

}
if (Math.max(s.length, t.length) % Math.min(s.length, t.length) === 0 ) {

if (s === t) {

var sub = '';

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

for(var j = 1; j < s.length; j++) {

if (s[j] === s.charAt(i)) {

sub = s.slice(s,j);

var repeater = Math.floor(s.length/sub.length);

if (sub.repeat(repeater) === s) {

return sub.length;

} else {

sub = s;

return sub.length;

} else {

if(s.indexOf(t.charAt(0)) == -1) {

return -1;

const count = Math.floor(s.length/t.length);

const getMinMaxStr = (s, t) => [s, t].sort((s, t) => s.length -


t.length);

const isDivisible = (s, t) => s === t.repeat(s.length / t.length);

const gcdOfStrings = (s, t) => {

const [min_str, max_str] = getMinMaxStr(s, t);

if (min_str !== max_str.substring(0, min_str.length)) return '';

let result= '';

for (let i = 1; i <= min_str.length; i++) {

if (max_str.length % i !== 0) continue;


const t = min_str.substring(0, i);

if (isDivisible(max_str, t) && isDivisible(min_str, t)) {

result = t;

return result.length;

};

} else return -1

}
https://allhackerranksolutionsbykaira.blogspot.com/search/label/HackerRank

https://awesomeopensource.com/project/Java-aid/Hackerrank-Solutions#data-structures

MEANDERING ARRAY

// Java program to print the array in given order

import java.util.Arrays;

public class GFG {

// Function which arrange the array.

static void rearrangeArray(int arr[], int n)

// Sorting the array elements

Arrays.sort(arr);

int[] tempArr = new int[n]; // To store modified array

// Adding numbers from sorted array to

// new array accordingly

int ArrIndex = 0;

// Traverse from begin and end simultaneously

for (int i = 0, j = n-1; i <= n / 2 || j > n / 2;

i++, j--) {

if(ArrIndex < n)

tempArr[ArrIndex] = arr[i];

ArrIndex++;

if(ArrIndex < n)

tempArr[ArrIndex] = arr[j];

ArrIndex++;

}
}

// Modifying original array

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

arr[i] = tempArr[i];

// Driver Code

public static void main(String args[])

int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 };

int n = arr.length;

rearrangeArray(arr, n);

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

System.out.print(arr[i]+" ");

DISTINCT DIGIT NUMBER

// Java implementation of brute

// force solution.

import java.util.LinkedHashSet;

class GFG

// Function to check if the given

// number has repeated digit or not

static int repeated_digit(int n)

LinkedHashSet<Integer> s = new LinkedHashSet<>();

// Traversing through each digit

while (n != 0)

int d = n % 10;
// if the digit is present

// more than once in the

// number

if (s.contains(d))

// return 0 if the number

// has repeated digit

return 0;

s.add(d);

n = n / 10;

// return 1 if the number has

// no repeated digit

return 1;

// Function to find total number

// in the given range which has

// no repeated digit

static int calculate(int L, int R)

int answer = 0;

// Traversing through the range

for (int i = L; i < R + 1; ++i)

// Add 1 to the answer if i has

// no repeated digit else 0

answer = answer + repeated_digit(i);

return answer;

}
// Driver Code

public static void main(String[] args)

int L = 80, R = 120;

// Calling the calculate

System.out.println(calculate(L, R));

TWIN STRING PROBLEM

import java.io.IOException;
import java.util.Scanner;

public class TwinStringProblem {


//creating method for checking two string
static boolean[] twins(String[] a, String[] b) {
boolean[] result = new boolean[a.length];

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


String aVal = a[i].toLowerCase();
String bVal = b[i].toLowerCase();
String[] aValArray = aVal.split("");
String[] bValArray = bVal.split("");

for (String s : aValArray) {


for (int index = 0; index < aValArray.length; index++) {
if (bValArray[index].equals(s)) { // checking whether the
index match or not
if ((s.indexOf(s) % 2 == 0 && index % 2 == 0) || // ch
ecking even values
(s.indexOf(s) % 2 != 0 && index % 2 != 0)) {
result[i] = false;
} else if ((s.indexOf(s) % 2 == 0 && index % 2 != 0)
|| (s.indexOf(s) % 2 != 0 && index % 2 == 0))
{
result[i] = true;
break;
}
}
}
}
}
return result;
}

//main Method
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);

int n = Integer.parseInt(in.nextLine().trim());
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextLine();
}

int m = Integer.parseInt(in.nextLine().trim());
String[] b = new String[m];
for (int i = 0; i < m; i++) {
b[i] = in.nextLine();
}

// call twins function


boolean[] results = twins(a, b);

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


System.out.println(results[i] ? "Yes" : "No");
}
}
}

ARRAY GAME
PRODUCT SORT
ANOTHER SOLUTION
VOWELS

RESTRUCTURED ARRAY
(another solution also available)
IS IT POSSIBLE
static LinkedList<Pair<Integer,Integer>> pairs = new LinkedList<Pair<Integer, Integer>>();

public static String isItPossible(Integer a, Integer b, Integer c, Integer d){

pairs.addLast(new Pair<Integer, Integer>(a,b));

while (!pairs.isEmpty()){

Pair<Integer,Integer> pair = pairs.poll();

Integer key = pair.getKey();

Integer value = pair.getValue();

if(key.equals(c) &&
value.equals(d)){

return "YES";

int sum=key+value;

if (sum<=c){

pairs.addLast(new Pair<Integer, Integer>(sum,value));

if (sum<=d){

pairs.addLast(new Pair<Integer, Integer>(key,sum));

return "NO";

VOWELS
ANOTHER SOLUTION
AUTOSCALE POLICY
MINIMUM SWAPS
ANOTHER SOLUTION
ARE ALMOST EQUIVALENT
ARRANGING COINS
COUNT DUPLICATE ELEMENTS

ANOTHER SOLUTION

public static int countDuplicate(List<int> numbers)

Dictionary<int,int> frequency = new Dictionary<int, int>();

for(int i=0; i<numbers.Count;i++){


if(frequency.ContainsKey(numbers[i])){

frequency[numbers[i]] = frequency[numbers[i]]+1;

else{

frequency.Add(numbers[i],1);

List<int> result = new List<int>();

foreach(var keys in frequency.Keys){

if(frequency[keys]>1){

result.Add(keys);

return result.Count;

BINARY NUMBER IN A LINKED LIST


DISTINCT NUMBERS
Competitive gaming
competetive gaming soln 2
Consolidated partitions

consolicadate partitions soln 2


Construction management
SLOWEST KEY PRESS
AREA OF THE BOX
CAR INHERITANCE

class WagonR extends Car{

int mileage;

public WagonR(Integer mileage){

super(false, "4");

this.mileage = mileage;

@Override

public String getMileage(){

String mil=Integer.toString(mileage);

return mileage+" kmpl";

class HondaCity extends Car{

int mileage;

public HondaCity(Integer mileage){

super(true, "4");

this.mileage = mileage;

@Override

public String getMileage(){

String mil=Integer.toString(mileage);

return mil+" kmpl";

}
class InnovaCrysta extends Car{

int mileage;

public InnovaCrysta(Integer mileage){

super(false, "6");

this.mileage = mileage;

@Override

public String getMileage(){

String mil=Integer.toString(mileage);

return mil+" kmpl";

}
PRISON BREAK

Check this also: https://leetcode.com/discuss/interview-question/1002082/twillio-oa-prison-break


COUNT STRING PERMUTATIONS
LIST INHERITANCE

https://allhackerranksolutionsbykaira.blogspot.com/2020/08/list-inheritance-hackerrank-
solution.html

DEVICE NAME SYSTEM

https://www.homeworklib.com/question/1486956/in-java-6-device-name-system-suggested-
problem

SPORT INHERITANCE

https://www.goeduhub.com/2885/program-inherit-cricketplayer-footballplayer-hockeyplayer
MERGE 2 ARRAYS
CONDENSED LIST

WAYS TO SUM
BALANCED ARRAY

EMPLOYEE IMPLEMENTATION

https://github.com/vadym-usatiuk/Hackerrank-Employee-
Implementation/blob/master/src/Solution.java
WORK SCHEDULE
COUNT OPTIONS

Count the number of ways to divide N in k s incrementally


https://www.geeksforgeeks.org/count-the-number-of-ways-to-divide-n-in-k-groups-
incrementally/
PERFECT SUBSTRING
LOAD BALANCING

https://leetcode.com/discuss/interview-question/719447/wish-online-assessment-question

CONSTRUCTION MANAGEMENT
IS POSSIBLE

ANOTHER SOLUTION

static LinkedList<Pair<Integer,Integer>> pairs = new LinkedList<Pair<Integer, Integer>>();

public static String isItPossible(Integer a, Integer b, Integer c, Integer d){

pairs.addLast(new Pair<Integer, Integer>(a,b));

while (!pairs.isEmpty()){

Pair<Integer,Integer> pair = pairs.poll();

Integer key = pair.getKey();

Integer value = pair.getValue();


if(key.equals(c) &&

value.equals(d)){

return "YES";

int sum=key+value;

if (sum<=c){

pairs.addLast(new Pair<Integer, Integer>(sum,value));

if (sum<=d){

pairs.addLast(new Pair<Integer, Integer>(key,sum));

return "NO";

}
GROUP DIVISION

SORT AN ARRAY
EFFICIENT SHIPPING
THE RESTRUCTURED ARRAY
PRODUCT OF MAXIMUM AND MINIMUM IN A DATA SET

You might also like