Friday, February 12, 2021

SKP's Java Problem Solving Series : Usernames Changes (HackerRank)

[Question/Problem Statement is Adapted from HackerRank]

Algorithms/Data Structures - [Problem Solving] 
There is a Specific Need for Changes in a List of Usernames. In a given List of Usernames - For Each Username - If the Username can be Modified and Moved Ahead in a Dictionary. The Allowed Modification is that Alphabets can change Positions in the Given Username.

Example
usernames[] = {"Aab", "Cat"}
 
"Aab" cannot be changed to another unique string matching the above rule - Hence, It can Never Find a Place Ahead in the Dictionary. Hence, Output will be "NO". "Cat" can be Changed to "Act", "Atc", "Tca", "Tac", "Cta" and Definitely "Act" will Find a Place Before "Cat" in the Dictionary. Hence, Output will be "YES".

[Function Description]
Complete the function possibleChanges in the Editor Below.
 
possibleChanges has the Following Parameters:
String usernames[n]: An Array of User Names
 
Returns String[n]: An Array with "YES" or "NO" Based on Feasibility
(Actual Question Says String Array, But Signature is List of Strings)


Constraints
• [No Special Constraints Exist, But Cannot Recall Exactly]


Input Format

"The First Line Contains an Integer, n, the Number of Elements in Usernames.", 
"Each Line of the n Subsequent Lines (where 0 < i < n) contains a String usernames[i]."        

[Sample Case 0 - Sample Input For Custom Testing]        
8      
Aab 
Cat
Pqrs
Buba
Bapg
Sungi
Lapg
Acba
       

Sample Output (Each Should Be on a Separate Line)
NO YES NO YES YES YES YES YES
  
______________ 
 
 
[Explanation of the Solution]
This is again a Good Question from Hacker Rank to Test Your Logic / Problem Solving Abilities. The Core Point to Handle is that For Each Combination of 2 Alphabets that Exists in the Username String > We Need to Check if the Latter Occuring Character (ASCII) is Less than the Former Occuring Character (ASCII). For Example in the String "Bapg" - For a Selection of "Ba" from "Bapg" - We have "a" Occuring Before "B" in the English Alphabet. We can Have Two Loops (One Nested) to Decide for a Combination of Each Two Alphabets. The Time Complexity of this Solution is O(n^2).
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

/*
* HackerRank Problem Solving - Speak Ur Mind, But Ride a Fast Horse.
* ~ Sumith Kumar Puri (c) 2021 ~ -- ~ Bengaluru, Karnataka, India ~
*
*/
class UsernamesChangesLogic {

public static List<String> possibleChanges(List<String> usernames) {

List<String> solutionStr = new ArrayList<String>();
boolean bobbysFlag = false;
for (String username : usernames) {

bobbysFlag = false;
String currName = username.toLowerCase();
for (int i = 0; i < currName.length(); i++) {

int a = currName.charAt(i);
for (int j = i + 1; j < currName.length(); j++) {

int b = currName.charAt(j);
if (b < a) {
bobbysFlag = true;
break;
}
}
if (bobbysFlag) {
solutionStr.add("YES");
break;
}
}
if (!bobbysFlag)
solutionStr.add("NO");
}

return solutionStr;
}
}

public class UsernamesChanges {

public static final String OUTPUT_PATH = "PROVIDE_ABSOLUTE_INPUT_FILE_NAME";

public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(OUTPUT_PATH));

int usernamesCount = Integer.parseInt(bufferedReader.readLine().trim());

List<String> usernames = IntStream.range(0, usernamesCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());

List<String> result = UsernamesChangesLogic.possibleChanges(usernames);

bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

bufferedReader.close();
bufferedWriter.close();
}
}

Happy Problem Solving using Java!

SKP's Java Problem Solving Series : Active Traders (HackerRank)

[Question/Problem Statement is the Property of HackerRank]

Algorithms/Data Structures - [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Acctive. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."


Example
n = 23
"customers = {"Bigcorp", "Bigcorp", "Acme", "Bigcorp", "Zork", "Zork", "Abe", "Bigcorp",  "Acme", "Bigcorp", "Bigcorp" , "Zork", "Bigcorp", "Zork", "Zork", "Bigcorp", "Acme", "Bigcorp", "Acme", "Bigcorp", "Acme",""Littlecorp" , "Nadircorp "}."


"Bigcorp had 10 Trades out of 23,which is 43.48% of the Total Trades."

"Both Acme and Zork had 5 trades,which is 21.74% of the Total Trades."

"The Littlecorp, Nadircorp and Abe had 1 Trade Each, which is 4.35%..."

"So the Answer is [""Acme"", "" Bigcorp  ,""Zork""] (In Alphabetical Order) Because only These Three Companies Placed atleast 5% of the Trades.


Function Description

Complete the Function mostActive in the Editor Below.

mostActive
has the following parameter:
String customers[n] : An Array Customer Names

(Actual Question Says String Array, But Signature is List of Strings)

Returns String[] : An Alphabetically Ascending Array


Constraints

• 1 < n < 10^5

• 1 < Length of customers[] < 20

• The First Character of customers[i] is a Capital English letter.

• All Characters of customers[i] except for the First One are Lowercase.

• Guaranteed that At least One Customer makes atleast 5% of Trades.



Input Format
            

"The First Line contains an integer, n, The Number of Elements in customers."       

"Each Line iof the n Subsequent Lines (where 0 s i< n) contains a string, customers[i]."      


Sample Case 0 Input For Custom Testing
20       

Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Beta      


Function mostActive      
customers[] size n =  20       

customers[] = [As Provided Above]       



Sample Output

Alpha       

Beta

Omega       



Explanation

"Alpha made 10 Trades out of 20 (50% of the Total), Omega made 9 Trades (45% of the Total). and Beta made 1 Trade (5% of the Total).All of them have met the 5% Threshold, so all the Strings are Returned in an Alphabetically Ordered Array."        

 
______________ 
 
 
[Explanation of the Solution]
This is Good Practice for the Brain for Problem Solving - Involves Simple Arithmetic and Mathematical Application. Ideally, A Programmer would want to Optimize the Solution in Space and Time (Which I Did Not :-)
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.IntStream;

/*
* HackerRank Problem Solving - Ain't a Horse that Can't be Rode
* Sumith Kumar Puri (c) 2021 - ~ Bengaluru, Karnataka, India ~
*
*/
class ActiveTradersLogic {

public static List<String> mostActive(List<String> customers) {

// How About Arrays or Custom LinkedList for a 'Very Fast' Traversal?
Map<String, Integer> customerMap = new TreeMap<String, Integer>();
List<String> solutionStr = new ArrayList<String>();
int customerMapSize = customers.size();

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

String customerKey = customers.get(i);

if (customerMap.containsKey(customerKey)) {

Integer customerCount = customerMap.get(customerKey);
customerMap.put(customerKey, ++customerCount);
} else {
customerMap.put(customerKey, 1);
}
}

Set<String> customerMapKeys = customerMap.keySet();
for (String customerKey : customerMapKeys) {

Integer customerCount = customerMap.get(customerKey);
double currentCustomerPercent = (double) (customerCount) / (double) customerMapSize;

if (currentCustomerPercent * 100 >= 5.0) {

solutionStr.add(customerKey);
}
}

return solutionStr;
}
}

public class ActiveTraders {

public static final String OUTPUT_PATH = "PROVIDE_ABSOLUTE_INPUT_FILE_NAME";

public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv(OUTPUT_PATH)));

int customersCount = Integer.parseInt(bufferedReader.readLine().trim());

List<String> customers = IntStream.range(0, customersCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());

List<String> result = ActiveTradersLogic.mostActive(customers);

bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

bufferedReader.close();
bufferedWriter.close();
}
}

Happy Problem Solving using Java!

Tuesday, February 2, 2021

SKP's Java Problem Solving Series : Refresh Java Lambdas (FP)

[Question/Problem Statement is the Property of Techgig]

Java Advanced - Lambda Expressions [www.techgig.com] 
Write the Following Methods that Return a Lambda Expression Performing a Specified Action: PerformOperation isOdd(): The Lambda Expression must return  if a Number is Odd or  If it is Even. PerformOperation isPrime(): The lambda expression must return  if a number is prime or  if it is composite. PerformOperation isPalindrome(): The Lambda Expression must return  if a number is a Palindrome or if it is not.

Input Format
Input is as Show in the Format Below (Deduce Unknowns!)

Input
3
1 3
2 7
3 7777

Constraints
NA

Output Format
Output is as Show in the Format Below (Deduce Unknowns!)

Output
ODD
PRIME
PALINDROME
______________ 
 
 
[Explanation of the Solution]
This is a Good Question to Refresh Java 8 Lambdas. In my Solution, I Implemented the Functional Interfaces within my main() Method and assigned it to Local Reference Variables.
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
 import java.util.Scanner;

/*    
 * Techgig Core Java Basics Problem - Knock Off Java Lambdas!   
 * Author: Sumith Puri [I Bleed Java!] // GitHub: @sumithpuri   
 */
interface LambdaYogi {
	public boolean opYog(int x);
}

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

                // you may choose to refactor, as this method
                // becomes really long and unmanageable #TODO
		LambdaYogi isOdd = a -> {
			boolean retFlag = false;
			if (a % 2 != 0)
				retFlag = true;
			return retFlag;
		};
		LambdaYogi isPrime = a -> {
			boolean retFlag = true;
			for (int i = 2; i < a - 1; i++) {
				if (a % i == 0) {
					retFlag = false;
					break;
				}
			}
			return retFlag;
		};
		LambdaYogi isPalindrome = a -> {
			boolean retFlag = false;
			String actStr = String.valueOf(a).trim();
			String revStr = new StringBuffer(actStr).reverse().toString();

			// using string basis, not mathematical
			if (actStr.equals(revStr))
				retFlag = true;
			return retFlag;
		};

		Scanner scanner = new Scanner(System.in);
		int val = scanner.nextInt();

		for (int i = 0; i < val; i++) {
			int op = scanner.nextInt();
			int no = scanner.nextInt();
			switch (op) {
			case 1: {
				if (isOdd.opYog(no))
					System.out.println("ODD");
				else
					System.out.println("EVEN");
				break;
			}
			case 2: {
				if (isPrime.opYog(no))
					System.out.println("PRIME");
				else
					System.out.println("COMPOSITE");
				break;
			}
			case 3: {
				if (isPalindrome.opYog(no))
					System.out.println("PALINDROME");
				else
					System.out.println("NONPALIN");
			}
			}
		}
	}
}

Happy Problem Solving using Java!

Saturday, January 30, 2021

SKP's Java Problem Solving Series : Simple Java Inheritance (OOPs)

[Question/Problem Statement is the Property of Techgig]
 
Java Inheritance / Simple OOPs [www.techgig.com] 
Create Two Classes:

BaseClass
The Rectangle class should have two data fields-width and height of int types. The class should have display()method, to print the width and height of the rectangle separated by space.

DerivedClass 
The RectangleArea class is Derived from Rectangle class, i.e., it is the Sub-Class of Rectangle class. The class should have read_input() method, to Read the Values of width and height of the Rectangle. The RectangleArea class should also Overload  the display() Method to Print the Area (width*height) of the Rectangle.

Input Format
The First and Only Line of Input contains two space separated Integers denoting the width and height of the Rectangle.

Constraints
1 <= width,height <= 10^3

Output Format
The Output Should Consist of Exactly Two Lines.
In the First Line, Print the Width and Height of the Rectangle Separated by Space. 
In the Second Line, Print the Area of the Rectangle.

______________ 
 
 
[Explanation of the Solution]
This is the Simplest of all OOPs Questions! Demonstration of Inheritance and Overriding (Very Loosely, Liskov Substitution of SOLID). 
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
 /*    
  * Techgig Core Java Basics Problem - Get Simple OOPs Right!  
  * Author: Sumith Puri [I Bleed Java!]; GitHub: @sumithpuri;  
  */   
     
  import java.io.*;   
  import java.util.*;   
   
   
  class Rectangle {  
   
    private int width;  
    private int height;  
   
    public void display() {  
   
      System.out.println(width + " " + height);  
    }  
   
    public int getWidth() {  
   
      return width;  
    }  
   
    public void setWidth(int width) {  
   
      this.width=width;  
    }  
   
    public int getHeight() {  
   
      return height;  
    }  
   
    public void setHeight(int height) {  
   
      this.height=height;  
    }  
  }  
   
  class RectangleArea extends Rectangle {  
   
    public void read_input() {  
   
     Scanner scanner = new Scanner (System.in);   
       
     setWidth(scanner.nextInt());   
     setHeight(scanner.nextInt());  
    }  
   
    public void display() {  
   
      super.display();  
      System.out.println(getWidth()*getHeight());  
    }  
  }  
     
  public class CandidateCode {   
     
   public static void main(String args[] ) throws Exception {   
     
     RectangleArea rectangleArea = new RectangleArea();  
     rectangleArea.read_input();  
   
     rectangleArea.display();  
   }   
 } 

Happy Problem Solving using Java!

Friday, January 29, 2021

SKP's Java Problem Solving Series : Monkeys in the Garden

[Question/Problem Statement is the Property of Techgig]

Monkeys in the Garden [www.techgig.com] 

In a garden, trees are arranged in a circular fashion with an equal distance between two adjacent trees. The height of trees may vary. Two monkeys live in that garden and they were very close to each other. One day they quarreled due to some misunderstanding. None of them were ready to leave the garden. But each one of them wants that if the other wants to meet him, it should take maximum possible time to reach him, given that they both live in the same garden.

The conditions are that a monkey cannot directly jump from one tree to another. There are 30 trees in the garden. If the height of a tree is H, a monkey can live at any height from 0 to H. Lets say he lives at the height of K then it would take him K unit of time to climb down to the ground level. Similarly, if a monkey wants to climb up to K height it would again take K unit of time. The time to travel between two adjacent trees is 1 unit. A monkey can only travel in a circular fashion in the garden because there is a pond at the center of the garden.

So the question is where should two monkeys live such that the traveling time between them is maximum while choosing the shortest path between them in any direction clockwise or anti-clockwise. You have to answer only the maximum traveling time.

Input Format
The First Line consists of Total Number of Trees (N). Each of the Following N Lines contains the Height of Trees in a Clockwise Fashion.

Constraints
1 <= Total Trees <= 30

1 <= Height Of Trees(H) <= 10000

Output Format
You must Print an Integer which will be the Maximum Possible Travel Time.

________________ 
 
 
[Explanation of the Solution]
Surprisingly, this Problem is under the Object Oriented Programming (OOP) Section of the Problems! Initially, I was on the Lookout for a 'Mathematically Superior' Solution. But Couldn't Reach Anywhere - In the End, I have a Simple Solution at O(n²). Iterate through Each 'Combination of Trees' and then Find the Clockwise and Anti-Clockwise Distance - At Each Iteration, the Minimum of the Two is Added to the Length of Each Tree. If this Value is Greater than the Maximum Path Length (Previous Iterations) - Replace the Maximum Path Length.
 
________________ 
 
[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
 /*   
  * Techgig Core Java Basics Problem - Monkeys in the Garden 
  * Author: Sumith Puri [I Bleed Java!]; GitHub: @sumithpuri
  */  
   
 import java.io.*;  
 import java.util.*;  
 import java.lang.Math;  
   
 public class CandidateCode {  
   
   public static void main(String args[] ) throws Exception {  
   
     Scanner scanner = new Scanner (System.in);  
       
     int n = scanner.nextInt();  
     int h[] = new int[n], max=0;  
     int cwLen=0,acLen=0,hiLen=0,toLen=0;  
   
     for(int i=0;i<n;i++) {  
       h[i] = scanner.nextInt();        
     }  
     max=h[0];  
   
     for(int i=0;i<n;i++) {  
   
       for(int j=i+1;j<n;j++) {  
         cwLen=Math.abs(((n-j)+i)); // clockwise  
         acLen=Math.abs((j-i));     // anti-clockwise  
         hiLen=(cwLen<=acLen)?(cwLen):(acLen);  
         toLen=hiLen+h[i]+h[j];     // path length    
         if(toLen>max) max=toLen;   // maximum path length  
       }  
     }  
          
     System.out.println (max);   
   }  
 }  
 
Happy Problem Solving using Java!