Cognizant hackerrank
DSA ASSESSMENT:
CDE /DSA is a algorithm level exams on hackerrank
It's differ from fse/gencnext on difficulty of code challenge .
All will be available in app
https://rasheed863.pythonanywhere.com/
search as cde in this android app
https://play.google.com/store/apps/details?id=com.master.askmastermaterial
if IOS proceed in paying via below button
1.post payment you will be routed to URL saying no file
2. save the URL you will getit only once
URL will be www.mega......?paymentid=..
you need to remove ?paymentid....
3. inorder to find your project click triple dot on right top of chrome ->find in page then type your project title partially
Support. : rodrasheed@gmail.com
For Java all CDE DSA,
you will get below post payment
- 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 PARANTHESIS
- GET MINIMUM
- FIND BEFORE MATRIX
- DIVICE NAME SYSTEM
- CONDENSED LIST
- GROUPING OPTIONS
- LIST INHERITANCE
- SPORTS INHERITANCE
- CRICKET SPORTS
- CAR INHERITANCE
- PRISON BREAK
- Matrix Summation
- Merge 2 arrays
- NUMBER OF MOVES Min Moves
- JAVA EXCEPTIONS: SECURING MESSAGES
- SUB STRING DIVISIBILITY
- MINIMUM SUM
- SMALLEST SET COVERING INTERVALS
- EVEN SUBARRAY
- GFG
- DIVISIBILITY OF STRING
click below Button
Programs also available Below
Cognizant Csharp HackerRank
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Result
{
//public static int MAX_CHAR=26;
public static bool check(int []arr,int k)
{
foreach(int val in arr)
{
if(val != 0 && val != k)
return false;
}
return true;
}
/*
* Complete the 'perfectSubstring' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING s
* 2. INTEGER k
*/
public static int perfectSubstring(string s, int k)
{
int res=0;
for(int i=0;i<s.Length;i++)
{
int []arr=new int[10];
for(int j=i;j<s.Length;j++)
{
if(j>i+(10*k))
break;
char ch=s[j];
arr[ch-'0']++;
if(check(arr,k))
res++;
}
}
return res;
}
}
class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string s = Console.ReadLine();
int k = Convert.ToInt32(Console.ReadLine().Trim());
int result = Result.perfectSubstring(s, k);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
def meanderingArray(nums):
meandered = []
nums = sorted(nums)
n = len(nums)
half = int(n/2)
if half%2 == 0:
half+=1
for i in range(half):
meandered.append(nums[n-1-i])
if n-1-i != i:
print(i)
meandered.append(nums[i])
if(n%2!=0):
meandered.append(nums[half])
return meandered
Cognizant Java Hackerrank
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 = 1 L;
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 %
.2 f ",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 %
.2 f ",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
}
Comments
Post a Comment