0% found this document useful (0 votes)
8 views

Coding Questions

The document discusses different Java programs and concepts like character counting, longest substring without repeating characters, producer consumer problem, checking if a number is prime, and solving the subset sum problem recursively. It includes code snippets in Java to implement these concepts.

Uploaded by

Aditya Kaushik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Coding Questions

The document discusses different Java programs and concepts like character counting, longest substring without repeating characters, producer consumer problem, checking if a number is prime, and solving the subset sum problem recursively. It includes code snippets in Java to implement these concepts.

Uploaded by

Aditya Kaushik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

//AABBBDDDCCC --> A2B3D3C3

import java. util. HashMap;


public class Main
{
public static void main(String[] args){

String str="pwwkew";

char[] chrStr=str.toCharArray();

HashMap<Character,Integer> map=new HashMap<Character,Integer>();

for(Character c : chrStr){

if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}
else{
map.put(c,1);
}

}
System.out.println(map);
}
}

===Using java 8====

Map<Character, Long> characterCountMap = input


.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(ch -
> ch, Collectors.counting()));

// "pwwkew" -> wke:3

import java.util.LinkedHashMap;

public class Main


{

public static void main (String[]args)


{
String str = "pwwkew";

int longestSubstringLength = 0;

String longestSubstring = "";

char[] chrStr = str.toCharArray ();

LinkedHashMap < Character, Integer > hash =

new LinkedHashMap < Character, Integer > ();


for (int i = 0; i < chrStr.length; i++) {
char c = chrStr[i];

if (!hash.containsKey (c)) {

hash.put (c, i);

}else {
i = hash.get (c);
hash.clear ();}

if (hash.size () > longestSubstringLength) {


longestSubstringLength = hash.size ();
longestSubstring = hash.keySet ().toString ();

}
}

System.out.println ("The longest substring : " + longestSubstring);


System.out.println ("The longest Substring Length : " +longestSubstringLength);

}
}

Date date;

this.date=new date(date.getTime());

Static ImmutableClass newInstance(String l1,String L2,String date){

return new ImmutableClass(l1,l2,date);


}

In wait - Lock is released

class printOddEvenNumbers{

int counter=1;
Int MAX= 20;
boolean odd;

public void printOdd(){

Synchronized(this){
while(counter<MAX){
while(!odd){

wait();
}

counter++;
odd=false;
notify();

public void printEven(){

thread.sleep(); // with try catch

while (counter<MAX){

while(odd){

wait();

}
}

import java.util.HashMap;
import java.util.Stack;

public class Main {

static HashMap<Character, Character> bMap;

static {
bMap = new HashMap<>();
bMap.put('(', ')');
bMap.put('[', ']');
bMap.put('{', '}');
}

static String isBalanced(String str) {

Stack<Character> stack = new Stack<>();


for(int i=0; i < str.length(); i++) {
Character ch = str.charAt(i);
if(bMap.containsKey(ch)) {
stack.push(ch);
} else if(stack.isEmpty() || ch != bMap.get(stack.pop())) {
return "NO";
}
}

return stack.isEmpty()? "YES": "NO";


}
public static void main(String[] args) {

String s="{{[[(())]]}}";
String result = isBalanced(s);
System.out.println(result);
} }

---count the frequency of words of List in Java 8

Map<StringLong>
collect=list.stream().collect(Collectors.groupingBy(function.Identity,Collectors.co
unting());

list.stream().filter(e1->e1.getSalary()>5000).collect(Collectors.asList());

list.stream().flatMap(e->Stream.of(e)).collect(Collectors.asList());

//Get count, min, max, sum, and average for numbers


List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream() .mapToInt((x) ->
x) .summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage()); }

===second highest salary

SELECT MAX (column_name) FROM table_name WHERE column_name NOT IN (SELECT Max
(column_name) FROM table_name)

select * from( select ename, sal, dense_rank() over(order by sal desc) r from
Employee) where r=3;

//producer Consumer

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

// Create a Main class for execution


public class Main {
public static void main(String[] args)
{

// Create an ArrayBlockingQueue object with capacity


// 4
BlockingQueue<Integer> bqueue
= new ArrayBlockingQueue<Integer>(4);

// Create 1 object each for producer


// and consumer and pass them the common
// buffer created above
producer p1 = new producer(bqueue);
consumer c1 = new consumer(bqueue);

// Create 1 thread each for producer


// and consumer and pass them their
// respective objects.
Thread pThread = new Thread(p1);
Thread cThread = new Thread(c1);

// Start both threads


pThread.start();
cThread.start();
}
}

class producer implements Runnable {

BlockingQueue<Integer> obj;

public producer(BlockingQueue<Integer> obj)


{
this.obj = obj;
}

@Override public void run()


{
for (int i = 1; i <= 4; i++) {
try {
obj.put(i);
System.out.println("Produced " + i);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class consumer implements Runnable {

BlockingQueue<Integer> obj;

int taken = -1;

public consumer(BlockingQueue<Integer> obj)


{
this.obj = obj;
}

@Override public void run()


{
while (taken != 4) {
try {
taken = obj.take();
System.out.println("Consumed " + taken);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class PrimeExample{


public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}

// A recursive solution for subset sum


// problem
class GFG {

// Returns true if there is a subset


// of set[] with sum equal to given sum
static boolean isSubsetSum(int set[],
int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;

// If last element is greater than


// sum, then ignore it
if (set[n - 1] > sum)
return isSubsetSum(set, n - 1, sum);

/* else, check if sum can be obtained


by any of the following
(a) including the last element
(b) excluding the last element */
return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n
- 1]);
}

/* Driver program to test above function */


public static void main(String args[])
{
int set[] = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n = set.length;
if (isSubsetSum(set, n, sum) == true)
System.out.println("Found a subset"
+ " with given sum");
else
System.out.println("No subset with"
+ " given sum");
}
}

You might also like