Showing posts with label hackerearth. Show all posts
Showing posts with label hackerearth. Show all posts

February 07, 2021

Write a java program to search a value from 2D array

package com.hack.javacode;

/**

 *  @Author Vishnu parasad varma
 */

class Solution22 {

public boolean searchMatrix(int[][] matrix, int target) {

boolean found = false;

int row = matrix.length;

if (row > 0) {

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

if (!found) {
for (int j = 0; j < matrix[i].length; ++j) {
System.out.println(matrix[i][j]);

if (target == matrix[i][j]) {

found = true;
break;
}
}
}
}

}

return found;
}

public static void main(String[] args) {
Solution22 s = new Solution22();
int[][] nums = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
int target = 38;
System.out.println(s.searchMatrix(nums, target));

}
}

January 28, 2021

Write a java program to rotate 1D array by n steps where n is a positive value

package com.leetcode.contest;

/**
 * Given an array, rotate the array to the right by k steps, where k is
 * non-negative.
 * 
 * Follow up:
 * 
 * Try to come up as many solutions as you can, there are at least 3 different
 * ways to solve this problem. Could you do it in-place with O(1) extra space?
 * 
 * @author Athul
 *
 */
class Solution21 {
public void rotate(int[] nums, int k) {

int len = nums.length;

int[] temp = new int[k];

int start = nums.length - k;

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

temp[i] = nums[start];
start++;
}

int[] temp2 = new int[start];
int j = 0;
for (int i = 0; i < start; i++) {

temp2[i] = nums[j];
j++;
}
j = 0;
for (int i = 0; i < len; i++) {

if (i < k) {
nums[i] = temp[i];
} else {
nums[i] = temp2[j];
j++;
}

}
System.out.println();
}

public static void main(String[] args) {
Solution21 s = new Solution21();
int[] nums = { -1 };
s.rotate(nums, 2);
}
}

July 14, 2020

Algorithm to find maximum profit on buying and selling from an array




Class MaximumProfit{

private int maxProfit(int[] prices) {
int profit = 0;
int minimum = 0;
for (int current = 1; current < prices.length; current++) {
int previous = current - 1;
int next = current + 1;
if (prices[previous] > prices[current]) {
minimum = current;
}
if (prices[previous] <= prices[current] && (next == prices.length ||prices[current] > prices[next]  )) {
profit += (prices[current] - prices[minimum]);
}
}
return profit;
}

public static void main(String[] args) {
// int[] a = { 7, 1, 5, 3, 6, 4 };
int[] a = { 1, 2, 3, 4, 5 };
// int []a = {7,6,4,3,1};
// int[] a = { 1, 2, 3, 4, 1 };
System.out.println(new MaximumProfit().maxProfit(a));
}

}

May 14, 2020

Sum up two Node to one in java


Our Idea is to sum up each elements in the given two nodes and create a new node.

/**
 * Sum up two Node to one in java
 */
package com.leetcode.algorithms;

/**
 * @author Cfed kozhikode
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Solution s = new Solution();

System.out.println(989+989);

ListNode l1 = new ListNode(9);
l1.next = new ListNode(9);
l1.next.next = new ListNode(9);

ListNode l2 = new ListNode(1);
/* l2.next = new ListNode(8);
l2.next.next = new ListNode(9);*/

ListNode a = s.addTwoNumbers(l1, l2);

// System.out.println(a);

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

}

}


package com.leetcode.algorithms;
/**
 * 
 * @author Bithesh
 *
 */
class Solution {

private ListNode parentNode = null;

private int carryforward = 0;

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int val1 = (null != l1) ? l1.val : 0;
int val2 = (null != l2) ? l2.val : 0;
int sum = val1 + val2 + carryforward;
carryforward = sum / 10;
int value = sum % 10;
parentNode = insertValue(parentNode, value);

ListNode n1 = (l1 == null || l1.next == null) ? null : l1.next;
ListNode n2 = (l2 == null || l2.next == null) ? null : l2.next;

if (n1 != null || n2 != null) {
addTwoNumbers(n1, n2);
}else if (carryforward > 0) {
parentNode = insertValue(parentNode, carryforward);
carryforward = 0;
}
return parentNode;
}

private ListNode insertValue(ListNode node, int data) {
if (node == null) {
return new ListNode(data);
} else {
node.next = insertValue(node.next, data);
}
return node;
}
}

/**
 * 
 */
package com.leetcode.algorithms;

/**
 * @author Bithesh
 *
 */
public class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}

October 14, 2019

Solving Eight Queen problem in chess board

/**
 *

Trying to solve eight queen problem in a chess board


 */
package com.codecreeks.solutions;

/**
 * @author Consumerfed kozhikode Information Technology Section
 *
 */
public class EightQueen {

/**
* @param args
*/
public static void main(String[] args) {

int[][] output = { { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 } };

int x = 0;
int y = 0;
int queen = 1;
int queenCount = 8;

while (queen <= queenCount) {
output[x][y] = 1;
x = x + 1;
y = y + 2;
if (y >= 8) {
y = (y % 8) + 1;
}
queen++;
}

for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
System.out.print(output[row][col] + " ");
}
System.out.println();
}

}

}

Output



1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1

Chess Boards available

So you must be wondering what is the revenue of our blog ? The commission (around 1 to 2 %) from amazon when any one purchase any amazon product through this blog. so we request you to buy any amazon product through this blog.


October 07, 2019

Number of characters to be removed to make two string anagram

/**
 * Anagram solver
Number of characters to be removed to make two string anagram
 */
package com.steffi.samples;

/**
 * @author Konzern Technologies
 *
 */
public class Anagram {

private int ptr = 0;
private StringBuilder sb = null;

public Anagram(StringBuilder sb) {
this.sb = sb;
}

/**
* @param args
*/
public static void main(String[] args) {
String str1 = "RAMU";
String str2 = "RAMESHA";
char[] char1 = str1.toCharArray();
char[] char2 = str2.toCharArray();
StringBuilder sb = new StringBuilder();
Anagram anagram = new Anagram(sb);
String ans = (str1.length() < str2.length()) ? anagram.compute(char1, char2) : anagram.compute(char2, char1);
System.out.println("Anagram : "+ans);
System.out.println((str1.length()+str2.length())-(ans.length()*2));

}

private String compute(char[] charA, char[] charB) {
for (int i = 0; i < charB.length; i++) {
if (charA[ptr] == charB[i]) {
sb.append(charA[ptr]);
charB[i] =' ';
break;
}
}
ptr++;
if (ptr >= (charA.length)) {
return sb.toString();
} else {
return compute(charA, charB);
}
}



}


outputs

RAM
5


Inputs Strings RAMU & RAMESH
Anagram :RAM
Characters to remove 4

Inputs Strings RAMUS & RAMESH
Anagram :RAMS
Characters to remove 3

Inputs Strings ARGENTINA & BRAZIL
Anagram :RAI
Characters to remove 9

Inputs Strings KONZERN & AMADEUS
Anagram :E
Characters to remove 12


Inputs Strings VIJI & ELIZA
Anagram :I
Characters to remove 7

Inputs Strings BLACK & MAMBA
Anagram :AB
Characters to remove 6





Tik Toc Toe in python, two player game, playing with computer complete source code available soon...

September 28, 2019

Finding the missing number in a sequential array with minimum complexity


Finding the missing number using binary search

Description :


/**
 * Find missing number in a sequence Minimum complexity (n Log n)
 *
 * input : {1,2,3,5}
 * output : 4
 */
package com.steffi.solutions;

import java.util.Arrays;

/**
 * @author Consumerfed Information Technology Section
 *
 */
public class MissingNumberArray {

private static int loopCount = 0;

public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int[] a = {1,2,3,4,6,7,8,9,10,11,12};
int len = a.length;
MissingNumberArray m = new MissingNumberArray();
int value = 0;
if(a[len-1]!=len) {
value = m.findMissingNumber(a, 0, len);
System.out.println(" The Missing number in the array :"+Arrays.toString(a)+" is "+value);
}else {
loopCount++;
System.out.println(" There is no missing number in the given array "+Arrays.toString(a));
}
System.out.println(" For "+len+" size array it tooks "+loopCount+" search to find the answer ");
System.out.println(" Complexity :"+len*Math.log(len));
System.out.println(" Time Taken : "+(System.currentTimeMillis() - startTime)+" ms");

}

private int findMissingNumber(int[] array, int startPstn, int endPstn) {
loopCount++;
int arraySize = endPstn - startPstn;
int position = startPstn + arraySize / 2;
if(arraySize==0) {
return position +1;
}else if (arraySize == 1) {
return array[position] + 1;
}
else if (array[position] != position + 1) {
return findMissingNumber(array, startPstn, position);
} else {
return findMissingNumber(array, position + 1, endPstn);

}
}
}

Output

 The Missing number in the array :[1, 2, 3, 5] is 4
 For 4 size array it tooks 2 search to find the answer
 Complexity :5.545177444479562
 Time Taken : 4 ms

 The Missing number in the array :[1, 2, 3, 5, 6, 7, 8, 9, 10] is 4
 For 9 size array it tooks 3 search to find the answer
 Complexity :19.775021196025975
 Time Taken : 4 ms

 The Missing number in the array :[1, 2, 3, 4, 5, 6, 7, 8, 10] is 9
 For 9 size array it tooks 3 search to find the answer
 Complexity :19.775021196025975
 Time Taken : 3 ms

 The Missing number in the array :[1, 2, 3, 4, 5, 6, 7, 8, 9, 11] is 10
 For 10 size array it tooks 3 search to find the answer
 Complexity :23.02585092994046
 Time Taken : 2 ms

 The Missing number in the array :[1, 2, 4, 5] is 3
 For 4 size array it tooks 3 search to find the answer
 Complexity :5.545177444479562
 Time Taken : 3 ms

 The Missing number in the array :[1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12] is 4
 For 11 size array it tooks 4 search to find the answer
 Complexity :26.376848000782076
 Time Taken : 3 ms

 The Missing number in the array :[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14] is 13
 For 13 size array it tooks 4 search to find the answer
 Complexity :33.34434164699998
 Time Taken : 3 ms

Buy any thing from amazon through us !!!

October 29, 2018

Bricks Game in Java

/**
 * Patlu and Motu works in a building construction, they have to put some number of bricks N from one place to another, and started doing their work. They decided , they end up with a fun challenge who will put the last brick.

They to follow a simple rule, In the i'th round, Patlu puts i bricks whereas Motu puts ix2 bricks.

There are only N bricks, you need to help find the challenge result to find who put the last brick.
Input:

First line contains an integer N.

Output:

Output "Patlu" (without the quotes) if Patlu puts the last bricks ,"Motu"(without the quotes) otherwise.

Constraints:

 */
package com.hackerearth.basicprograming;

import java.util.Scanner;

/**
 * @author consumerfed
 *
 */
public class BricksGame {

/**
* @param args
*/
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int noOfBricks = sc.nextInt();
String currentPerson = "P";
int step = 1;
int intialValue = 1;
int bricksMoved = 0;

while ((noOfBricks - bricksMoved) > 0) {
if ((step % 2) != 0) {
currentPerson = "P";
bricksMoved = bricksMoved + intialValue;
} else {
currentPerson = "M";
bricksMoved = bricksMoved + (intialValue * 2);
intialValue = intialValue + 1;
}
step = step + 1;
}

System.out.println(currentPerson);
}

}

Output

13 bricks are there :
Patlu Motu
1 2
2 4
3 1 ( Only 1 remains)
Hence, Motu puts the last one.

E Maze In Program Logic in java

/**
 * Ankit is in maze. The command center sent him a string which decodes to come out from the maze. He is initially at (0, 0). String contains L, R, U, D denoting left, right, up and down. In each command he will traverse 1 unit distance in the respective direction.
 * For example if he is at (2, 0) and the command is L he will go to (1, 0).
 *
 * SAMPLE INPUT : LLRDDR
 * SAMPLE OUTPUT : 0 -2
 *
 */
package com.hackerearth.basicprograming;
import java.util.Scanner;
/**
 * @author consumerfed
 *
 */
public class EMazeIn {

/**
* @param args
*/
public static void main(String[] args) {
int x = 0;
int y = 0;
Scanner sc = new Scanner(System.in);
String traverse = sc.nextLine();
for(int i=0;i<traverse.length();i++) {
char movement = traverse.charAt(i);
switch (movement) {
case 'L':
x =x -1;
break;
case 'D':
y = y -1;
break;
case 'R':
x = x + 1;
break;
case 'U':
y = y + 1;
break;

default:
break;
}
}
System.out.println( x + " "+y );
}
}

SAMPLE INPUT : LLRDDR

SAMPLE OUTPUT : 0 -2

Facebook comments